我写了一个小类来尝试使用自定义__getattr__
方法,每次运行它时,我都会收到一个属性错误:
class test:
def __init__(self):
self.attrs ={'attr':'hello'}
def __getattr__(self, name):
if name in self.attrs:
return self.attrs[name]
else:
raise AttributeError
t = test()
print test.attr
那么输出是:
Traceback (most recent call last):
File "test.py", line 11, in <module>
print test.attr
AttributeError: class test has no attribute 'attr'
是什么赋予了?我认为在引发属性错误之前调用了getattr ?