python中_getattribute_异常后的调用顺序是什么

578次阅读
没有评论
python中_getattribute_异常后的调用顺序是什么

在多个函数同时调用时,不免要考虑它们的先后执行顺序。那么假如我们的函数运行时出现了错误,程序继续运行下去的结果会是怎样呢?下面我们以__getattribute__为例,同时结合之前所学的__getattr__,探寻__getattribute__出错后的调用顺序是怎样发生的,接下来我们一起看看具体内容。

1.__getattribute__() 在查找真正要访问的属性之前就被调用了,无论该属性是否存在

使用__getattribute__()要特别注意,因为如果你在它里面不知何故再次调用了__getattribute__(),你就会进入无穷递归。为了避免这种情况,如果你想要访问任何它需要的属性,应该总是调用祖先类的同名方法:比如super(obj, self).__getattribute__(attr)

程序员主要使用__getattribute__()来实现某些拦截功能,特别是数据访问保护。

class User:
    def __init__(self, info={}):
        self.info = info
 
    def __getattr__(self, item):
        return self.info[item]
 
    # def __getattribute__(self, item):
    #     return "mike"

2.如果你的类同时存在__getattr__()和__getattribute__(),并且如果__getattribute__()抛出了AttributeError异常,那么该异常将会被忽略,getattr()依然会被调用。

下面是一个例子:

class Count(object):
    def __init__(self, mymin, mymax):
        self.mymin = mymin
        self.mymax = mymax
        self.current = None
 
    def __getattr__(self, item):
        self.__dict__[item] = 0
        return 0
 
    def __getattribute__(self, item):
        if item.startswith('cur'):
            raise AttributeError
        return object.__getattribute__(self, item)
        # or you can use ---return super().__getattribute__(item)
        # note this class subclass object
 
 
obj1 = Count(1, 10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.current)
 
# 1
# 10
# 0

通过上面的代码我们可以看出,__getattribute__的出错会被忽略,程序依然会往下执行,感兴趣的小伙伴也来试试吧。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-16发表,共计1335字。
新手QQ群:570568346,欢迎进群讨论 Python51学习