问题:如何在不破坏默认行为的情况下在Python中重写__getattr__?
我想重写__getattr__
类上的方法以执行某些操作,但我不想破坏默认行为。
正确的方法是什么?
回答 0
覆盖__getattr__
应该没问题- __getattr__
仅可作为最后的选择,即,如果实例中没有与名称匹配的属性。例如,如果您访问foo.bar
,则__getattr__
仅当foo
没有调用属性时才会被调用bar
。如果该属性是您不想处理的属性,请引发AttributeError
:
class Foo(object):
def __getattr__(self, name):
if some_predicate(name):
# ...
else:
# Default behaviour
raise AttributeError
但是,与不同的是__getattr__
,__getattribute__
将首先调用(仅适用于新样式类,即从对象继承的类)。在这种情况下,您可以保留默认行为,如下所示:
class Foo(object):
def __getattribute__(self, name):
if some_predicate(name):
# ...
else:
# Default behaviour
return object.__getattribute__(self, name)
回答 1
class A(object):
def __init__(self):
self.a = 42
def __getattr__(self, attr):
if attr in ["b", "c"]:
return 42
raise AttributeError("%r object has no attribute %r" %
(self.__class__.__name__, attr))
>>> a = A()
>>> a.a
42
>>> a.b
42
>>> a.missing
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in __getattr__
AttributeError: 'A' object has no attribute 'missing'
>>> hasattr(a, "b")
True
>>> hasattr(a, "missing")
False
回答 2
为了扩展Michael的答案,如果您想使用来维持默认行为__getattr__
,可以这样做:
class Foo(object):
def __getattr__(self, name):
if name == 'something':
return 42
# Default behaviour
return self.__getattribute__(name)
现在,异常消息更具描述性:
>>> foo.something
42
>>> foo.error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __getattr__
AttributeError: 'Foo' object has no attribute 'error'