__getattr__和__getattribute__之间的区别 [英] Difference between __getattr__ vs __getattribute__
问题描述
我试图了解何时使用__getattr__
或__getattribute__
. 文档提及__getattribute__
适用于新样式类.什么是新型类?
__getattr__
和__getattribute__
之间的主要区别在于,仅当找不到通常的属性时才调用__getattr__
.这对于实现缺少属性的后备方法很有用,并且可能是您想要的两个之一.
在查看对象的实际属性之前,将调用 __getattribute__
,因此正确实现可能会比较棘手.您可以非常轻松地进行无限递归.
新式类是从object
派生的,旧式类是Python 2.x中没有显式基类的类.但是,在__getattr__
和__getattribute__
之间进行选择时,旧样式类与新样式类之间的区别并不是很重要.
您几乎可以肯定想要__getattr__
.
I am trying to understand when to use __getattr__
or __getattribute__
. The documentation mentions __getattribute__
applies to new-style classes. What are new-style classes?
A key difference between __getattr__
and __getattribute__
is that __getattr__
is only invoked if the attribute wasn't found the usual ways. It's good for implementing a fallback for missing attributes, and is probably the one of two you want.
__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.
New-style classes derive from object
, old-style classes are those in Python 2.x with no explicit base class. But the distinction between old-style and new-style classes is not the important one when choosing between __getattr__
and __getattribute__
.
You almost certainly want __getattr__
.
这篇关于__getattr__和__getattribute__之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!