class F(object):
    def __init__(self):
        self.name = 'A'
    def __getattr__(self, item):
        if item == 'age':
            return 40
        elif item == 'haha':
            return 'good'
        else:
            raise AttributeError('没有这个属性')
    def __getattribute__(self, item):
        print('获取属性,方法', item)
        return object.__getattribute__(self, item)
f = F()
print(f.age)
print(f.haha)

  

获取属性,方法 age   <<<<<print(f.age)时调用getattribute魔法方法
40                               <<<<<print(f.age)时发现age不是f的属性,则调用getattribute魔法方法
获取属性,方法 haha 
good

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

 

此处魔法方法是__getattribute__(self, item)和__getattr__(self, item):

getattribute (print(ob.name) -- obj.func())当访问对象的属性或者是方法的时候触发

getattr 拦截运算(obj.xx),对没有定义的属性名和实例,会用属性名作为字符串调用这个方法

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄