我已经编写了这个小班,尝试使用自定义__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 ?
答案 0 :(得分:8)
由于班级test
不将attr
作为属性,因此实例t
执行:
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 t.attr
答案 1 :(得分:4)
您必须查询实例(t
)上的属性,而不是类(test
):
>>> t = test()
>>> print t.attr
hello