栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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__的出错会被忽略,程序依然会往下执行,感兴趣的小伙伴也来试试吧。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/11308.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号