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 @   wztshine  阅读(332)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示