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时会因为循环调用崩溃

此文仅为鄙人学习笔记之用,朋友你来了,如有不明白或者建议又或者想给我指点一二,请私信我。liuw_flexi@163.com/QQ群:582039935. 我的gitHub: (学习代码都在gitHub) https://github.com/nwgdegitHub/
原文地址:https://www.cnblogs.com/liuw-flexi/p/9007683.html