编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

刘心向学(33):Python中的__getattr__与__getattribute__

wxchong 2025-07-09 18:06:31 开源技术 2 ℃ 0 评论

分享兴趣,传播快乐,

增长见闻,留下美好!

亲爱的您,这里是LearningYard新学苑。

今天小编为大家带来文章 “刘心向学(33):Python中的__getattr__与__getattribute__”

欢迎您的访问。

Share interest, spread happiness,

Increase knowledge, leave a beautiful!

Dear, this is LearningYard Academy.

Today, the editor brings you an article. “Liu Xinxiangxue (33):
__getattr__ and __getattribute__”

Welcome to your visit.

一、思维导图(Mind Map)

二、引言(Introduction)

在 Python 面向对象编程中,属性访问是常见操作。而 __getattr____getattribute__ 是两个关键的魔法方法,它们控制了对象属性的查找和访问逻辑。

In Python's object-oriented programming, attribute access is a common operation. The two key magic methods, __getattr__ and __getattribute__, control the logic of looking up and accessing an object’s attributes.


三、属性访问流程简介(Introduction to the Attribute Lookup Process)

当访问一个对象的属性时,Python 按照以下顺序查找:

When accessing an attribute of an object, Python follows this lookup order:

实例的 __dict__

Instance’s __dict__

类的 __dict__

Class’s __dict__

父类的 __dict__

Parent class’s __dict__

如果仍未找到,调用 __getattr__(如果定义)

If still not found, call __getattr__ (if defined)

其中:

__getattribute__

在每次访问属性时都会被调用。

__getattribute__ is called every time an attribute is accessed.

__getattr__

只有在属性不存在时才会触发。

__getattr__ is only triggered when the attribute does not exist.


四、__getattribute__方法(The __getattribute__ Method)

作用:拦截所有属性访问请求。

Purpose: Intercept all attribute access requests.

Python浅色版本classMyClass:
def__init__(self):
        self.x = 10

def__getattribute__(self, name):
print(f"访问属性 {name}")
returnsuper().__getattribute__(name)

注意:重写此方法时要小心避免无限递归,建议使用 super() 调用父类实现。


Note: Be careful to avoid infinite recursion when overriding this method. It is recommended to use super()to call the parent class implementation.

五、__getattr__方法(The __getattr__Method)

作用:处理未定义的属性访问。

Purpose: Handle accesses to undefined attributes.

Python浅色版本classDynamicProxy:
def__getattr__(self, name):
print(f"访问未知属性 {name}")
returnlambda: f"{name} 被调用"

适合用于动态生成属性或方法、懒加载等场景。


Suitable for dynamically generating attributes or methods, lazy loading, and similar scenarios.


六、典型应用示例(Typical Use Case Examples)

1. 属性安全访问(Safe Attribute Access)

Python浅色版本classSafeDictAccess:
def__init__(self, data):
        self.data = data

def__getattribute__(self, name):
try:
returnsuper().__getattribute__(name)
except AttributeError:
return self.data.get(name)

2. 链式调用 API(Fluent / Chainable API)

Python浅色版本classChainable:
def__init__(self):
        self.path = []

def__getattr__(self, name):
        self.path.append(name)
return self

defget_path(self):
return"/".join(self.path)

3. 构建远程调用代理(Building a Remote Call Proxy)

Python浅色版本classRPCClient:
def__getattr__(self, method):
defcall(*args, **kwargs):
returnf"调用 {method}({args}, {kwargs})"
return call

七、注意事项(Important Notes)

尽量避免直接重写 __getattribute__,除非必要。

Avoid overriding __getattribute__ directly unless necessary.

使用 super() 避免无限递归。

Use super() to avoid infinite recursion.

优先考虑使用 __getattr__ 来实现动态行为。

Prefer using __getattr__ to implement dynamic behavior.

注意与描述符(如 property)之间的交互。

Be aware of interactions with descriptors (e.g., property).


八、结语(Conclusion)

掌握 __getattr____getattribute__ 的区别与用法,有助于我们编写更灵活、可扩展的 Python 类。无论是构建框架、设计接口,还是实现高级特性,这两个魔法方法都提供了强大的支持。

Understanding the differences and usage of __getattr__ and __getattribute__ helps us write more flexible and extensible Python classes. Whether building frameworks, designing APIs, or implementing advanced features, these two magic methods provide powerful capabilities.


今天的分享就到这里了。

如果您对文章有独特的想法,

欢迎给我们留言,

让我们相约明天。

祝您今天过得开心快乐!

That's all for today's sharing.

If you have a unique idea about the article,

please leave us a message,

and let us meet tomorrow.

I wish you a nice day!

参考资料:通义千问

参考文献:Beazley, D., & Jones, B. K. (2019). Python Cookbook (3rd ed.). O'Reilly Media.

Hettinger, R. (2019). Transforming Code into Beautiful, Idiomatic Python. PyCon US.

本文由LearningYard新学苑整理发出,如有侵权请在后台留言沟通! LearningYard新学苑

文字:song

排版:song

审核|qiu

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表