美文网首页
描述符 descriptor

描述符 descriptor

作者: 午字横 | 来源:发表于2023-05-01 13:22 被阅读0次

1:__getattr____getattribute__

由于__getattr__只针对未定义属性的调用,所以它可以在自己的代码中自由地获取其他属性,而__getattribute__针对所有的属性运行,因此要十分注意避免在访问其他属性时,再次调用自身的递归循环。

class ClassA:
    x = 'a'
    def __init__(self):
        self.y = 'b'

    def __getattribute__(self, item):
        print(item)
        pass
    def __getattr__(self, item):
        print("__getattr")
        return '__getattr__'+item

if __name__ == '__main__':
    a = ClassA()
    print(a.x)  # a

    # 使用实例对象直接访问实例存在的实例属性时,不会调用__getattr__方法
    print(a.y)  # b

    # 使用实例对象直接访问实例不存在的实例属性时,会调用__getattr__方法
    print(a.z)  # __getattr__



>>>
x
None
y
None
z
None

__getattribute____getattr__都是对访问属性时的特殊操作
  • __getattr__只针对未定义属性的调用
  • __getattribute__针对所有的属性运行
  • 当代码中同时重写__getattr____getattribute__时候,不会调用__getattr__

2023-04-28

相关文章

网友评论

      本文标题:描述符 descriptor

      本文链接:https://www.haomeiwen.com/subject/fjqijdtx.html