Python 中内建属性 __getattribute__

参考自:https://blog.csdn.net/yitiaodashu/article/details/78974596

__getattribute__是属性访问拦截器
,就是当这个类的属性被访问时,会自动调用类的__getattribute__方法

Python中只要定义了继承object的类,就默认存在属性拦截器,只不过是拦截后没有进行任何操作,而是直接返回。所以我们可以自己改写__getattribute__方法来实现相关功能,比如查看权限、打印log日志等。

注意点:

防止在内建属性中循环调用:
比如:
class Tree(object):
    def __init__(self,name):
        self.name = name
        self.cate = "plant"
    def __getattribute__(self,obj):
        if obj.endswith("e"):
            return object.__getattribute__(self,obj)
        else:
            return self.call_wind()
    def call_wind(self):
        return "树大招风"
aa = Tree("大树")
print(aa.name)#因为name是以e结尾,所以返回的还是name,所以打印出"大树"
print(aa.wind)

运行到aa.wind时会因为循环调用崩溃

猜你喜欢

转载自www.cnblogs.com/liuw-flexi/p/9007683.html