python 新式类的 __getattribute__

这个方法定义在object中,所以所有的新式类都继承有该方法,所有的新式类的实例在获取属性value的时候都会调用该方法,为了验证这一结论,我们重写一下该方法:

class C(object):
    a = 'abc'
    def __getattribute__(self, *args, **kwargs):
        print("__getattribute__() is called")
        return object.__getattribute__(self,args[0])
        
    def __getattr__(self, name):
        print ('hhh')
        if name == 'adult':
            return True
            
        else: raise AttributeError(name)
    

a=C()
c=a.a#打印__getattribute__ is called 返回属性的value'abc'
b=getattr(a,'adult',7)#先打印__getattribute__ is called,后打印hhh,b为True
print b

 而旧式类则无次方法,对象获取属性值时也不是通过这个方法获取的,而是另一套机智

猜你喜欢

转载自www.cnblogs.com/saolv/p/9493133.html