Answers:
覆盖__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)
__getattr__
任何想法该怎么做?(AttributeError: 'super' object has no attribute '__getattr__'
)
AttributeError
在异常args中有了一个没有属性上下文的。
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
self.__class__.__name__
应该使用self.__class__
该类,以防万一该类被覆盖__repr__
为了扩展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'
__getattr__
和__getattribute__
?