python的魔法方法

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

 

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

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

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

posted @ 2019-04-09 10:13  月亮上的石头  阅读(207)  评论(0编辑  收藏  举报