了解__getattr__和__getattribute__之间的区别 [英] Understanding the difference between __getattr__ and __getattribute__
问题描述
我试图理解__getattr__
和__getattribute__
之间的区别,但是,我没有做到这一点.
I am trying to understand the difference between __getattr__
and __getattribute__
, however, I am failing at it.
答案堆栈溢出"问题
The answer to the Stack Overflow question Difference between __getattr__
vs __getattribute__
says:
在查看以下内容的实际属性之前,先调用
__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.
我绝对不知道那是什么意思.
I have absolutely no idea what that means.
然后继续说:
您几乎可以肯定想要
__getattr__
.
为什么?
我了解到,如果__getattribute__
失败,则会调用__getattr__
.那么,为什么有两种不同的方法做同样的事情呢?如果我的代码实现了新样式类,我应该使用什么?
I read that if __getattribute__
fails, __getattr__
is called. So why are there two different methods doing the same thing? If my code implements the new style classes, what should I use?
我正在寻找一些代码示例来清除此问题.我已尽我最大的能力来搜索Google,但我发现的答案并未彻底讨论该问题.
I am looking for some code examples to clear this question. I have Googled to best of my ability, but the answers that I found don't discuss the problem thoroughly.
如果有任何文档,我准备阅读.
If there is any documentation, I am ready to read that.
推荐答案
一些基本知识.
对于对象,您需要处理其属性.通常,我们执行instance.attribute
.有时我们需要更多的控制权(当我们事先不知道属性名称时).
Some basics first.
With objects, you need to deal with its attributes. Ordinarily we do instance.attribute
. Sometimes we need more control (when we do not know the name of the attribute in advance).
例如,instance.attribute
将变为getattr(instance, attribute_name)
.使用此模型,我们可以通过提供 attribute_name 作为字符串来获取属性.
For example, instance.attribute
would become getattr(instance, attribute_name)
. Using this model, we can get the attribute by supplying the attribute_name as a string.
您还可以告诉类如何处理它未显式管理的属性,并通过__getattr__
方法来实现.
You can also tell a class how to deal with attributes which it doesn't explicitly manage and do that via __getattr__
method.
每当您请求尚未定义的属性时,Python都会调用此方法,因此您可以定义使用该方法的方法.
Python will call this method whenever you request an attribute that hasn't already been defined, so you can define what to do with it.
一个经典的用例:
class A(dict):
def __getattr__(self, name):
return self[name]
a = A()
# Now a.somekey will give a['somekey']
注意事项和__getattribute__
的使用
如果您需要捕获每个属性是否存在 ,请改用__getattribute__
.区别在于__getattr__
仅针对实际上不存在的属性被调用.如果直接设置属性,则引用该属性将在不调用__getattr__
的情况下检索该属性.
Caveats and use of __getattribute__
If you need to catch every attribute regardless whether it exists or not, use __getattribute__
instead. The difference is that __getattr__
only gets called for attributes that don't actually exist. If you set an attribute directly, referencing that attribute will retrieve it without calling __getattr__
.
__getattribute__
一直被调用.
这篇关于了解__getattr__和__getattribute__之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!