Python __getattr__、__setattr__

__getattribute____getattr____setattr__

当我们调用 obj.xxx 来访问 obj 的属性时,会自动调用 obj__getattribute__ 方法来返回属性的值。

只有显式的调用 __getattr__,或者当 __getattribute__ 抛出 AttributeError 时,__getattr__ 才会执行。__getattr__也是用来获取对象的属性的。

当我们使用 obj.xxx = yyy 来创建属性时,会自动调用 obj__setattr__ 方法来为属性赋值。

class A(object):
    def __init__(self):
        self.name = "wzt"
        self.age = 20

    def __getattribute__(self, item):
        print("Get attribute: ", item)
        if item != "age":
            # 不能使用 self.__dict__[item] 来获取属性,因为访问 self.__dict__ 也会触发 self.__getattribute__,造成递归错误 
            # return self.__dict__[item]
            return super().__getattribute__(item)
        else:
            raise AttributeError  # 当遇到 AttributeError 时,会自动尝试调用下面的 __getattr__ 来获取属性

    def __getattr__(self, item):
        print("Get attr: ", item)
        return self.__dict__[item]

    def __setattr__(self, key, value):
        print(key, value)
        # 不能使用 self.key = value 来赋值,因为它会触发 self.__setattr__ 自身,会造成递归错误
        # self.key = value  
        self.__dict__[key] = value


a = A()
print(a.name)
print(a.age)
a.ad = 222
print(a.ad)
posted @ 2019-12-30 09:42  wztshine  阅读(328)  评论(0编辑  收藏  举报