__getattr__和__getattribute__

python有两个魔法方法__getattr__和__getattribute__,都是用来获取对象属性,但很容易混淆

class Parent(object):
    def __init__(self):
        pass

    def __getattr__(self, item):
        print ("This is Parents __getattr__")
        return item

    def __getattribute__(self, item):
        print ("This is Parents __getattribute__")
        return item

class Child(Parent):
    def __init__(self):
        super(Child, self).__init__()

    def __getattr__(self, item):
        print ("This is Child __getattr__")
        return item

    def __getattribute__(self, item):
        print ("This is Child __getattribute__")
        return item

p=Parent()
print (p.x)
print ("==========parenets===========")
c=Child()
print (c.y)
This is Parents __getattribute__
x
==========parenets===========
This is Child __getattribute__
y

结论: __getattribute__优先于__getattr__

          __getattribute__: 子类找到__getattribute__就用子类的,子类没有就去父类找,父类找到__getattribute__就用父类的,父类还找不到就调用子类的__getattr__方法

           __getattr__:        子类找到__getattr__就调用子类的,子类没有就调用父类__getattr__

          两个方法都找不到就会报错AttributeError: 'Parent' object has no attribute 'x'

          

 

posted @ 2022-11-16 21:20  腹肌猿  阅读(51)  评论(0编辑  收藏  举报