如何在不破坏默认行为的情况下在Python中重写__getattr__? [英] How do I override __getattr__ in Python without breaking the default behavior?
问题描述
我想重写类上的__getattr__
方法以执行一些幻想,但我不想破坏默认行为.
I want to override the __getattr__
method on a class to do something fancy but I don't want to break the default behavior.
正确的方法是什么?
推荐答案
覆盖__getattr__
应该没问题-__getattr__
仅作为最后的选择,即,如果实例中没有与名称匹配的属性.例如,如果您访问foo.bar
,则仅当foo
没有名为bar
的属性时,才会调用__getattr__
.如果该属性是您不想使用的属性,请提高AttributeError
:
Overriding __getattr__
should be fine -- __getattr__
is only called as a last resort i.e. if there are no attributes in the instance that match the name. For instance, if you access foo.bar
, then __getattr__
will only be called if foo
has no attribute called bar
. If the attribute is one you don't want to handle, raise AttributeError
:
class Foo(object):
def __getattr__(self, name):
if some_predicate(name):
# ...
else:
# Default behaviour
raise AttributeError
但是,与__getattr__
不同,__getattribute__
将首先被调用(仅适用于新样式类,即从对象继承的样式类).在这种情况下,您可以保留默认行为,如下所示:
However, unlike __getattr__
, __getattribute__
will be called first (only works for new style classes i.e. those that inherit from object). In this case, you can preserve default behaviour like so:
class Foo(object):
def __getattribute__(self, name):
if some_predicate(name):
# ...
else:
# Default behaviour
return object.__getattribute__(self, name)
有关更多信息,请参见 Python文档.
See the Python docs for more.
这篇关于如何在不破坏默认行为的情况下在Python中重写__getattr__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!