python - 了解 __getattr__ 和 __getattribute__ 之间的区别

我试图了解 __getattr____getattribute__ 之间的区别,但是我没能做到。

answer堆栈溢出问题 Difference between __getattr__ vs __getattribute__ 说:

__getattribute__ is invoked before looking at the actual attributes on the object, and so can be tricky to implement correctly. You can end up in infinite recursions very easily.

我完全不知道这意味着什么。

然后它继续说:

You almost certainly want __getattr__.

为什么?

我读到如果 __getattribute__ 失败,则调用 __getattr__ 。那么为什么有两种不同的方法做同样的事情呢?如果我的代码实现了新的样式类,我应该使用什么?

我正在寻找一些代码示例来解决这个问题。我已尽我所能在 Google 上搜索,但我找到的答案并没有彻底讨论这个问题。

如果有任何文档,我准备阅读。

最佳答案

先了解一些基础知识。

对于对象,您需要处理它们的属性。通常,我们使用 instance.attribute。有时我们需要更多的控制(当我们事先不知道属性的名称时)。

例如,instance.attribute 将变为 getattr(instance, attribute_name)。使用此模型,我们可以通过提供 attribute_name 作为字符串来获取属性。

__getattr__的使用

你还可以告诉一个类如何处理它没有明确管理的属性,并通过 __getattr__ 方法来做到这一点。

每当您请求尚未定义的属性时,Python 都会调用此方法,因此您可以定义如何处理它。

一个经典的用例:

class A(dict):
    def __getattr__(self, name):
       return self[name]
a = A()
# Now a.somekey will give a['somekey']

__getattribute__

的注意事项和使用

如果您需要捕获每个属性无论它是否存在,请改用 __getattribute__。不同之处在于 __getattr__ 只为实际不存在的属性调用。如果您直接设置属性,则引用该属性将在不调用 __getattr__ 的情况下检索它。

__getattribute__ 一直被调用。

https://stackoverflow.com/questions/4295678/

相关文章:

linux - grep 不显示路径/文件 :line

linux - 如何为 wget 设置代理?

linux - 如何在 Linux 中在段错误时生成核心转储?

python - 如何将数据框行分组到 Pandas groupby 中的列表中

python - 安装 python 时在 $PATH 中找不到可接受的 C 编译器

regex - 用 grep 匹配一行中的两个字符串

python - numpy.random.seed(0) 做什么?

python - 省略号 [...] 在列表中是什么意思?

python - 如何将空列添加到数据框中?

linux - 保持 SSH session 处于事件状态