我的代码有错误(类似于下面的错误),但结果对我来说似乎很奇怪。有人可以向我解释如何调用getattr的名称是“hello”吗?python中很奇怪的__getattr__行为
class A(object):
def __getattr__(self, name):
print name
assert name != 'hello'
return self.hello
class C(object):
def __init__(self):
class B(A):
@property
def hello(self_):
return self.durp
self.b = B()
c = C()
print c.b.bang
的这个输出是:
bang
hello
Traceback (most recent call last):
File "test.py", line 17, in <module>
print c.b.bang
File "test.py", line 5, in __getattr__
return self.hello
File "test.py", line 4, in __getattr__
assert name != 'hello'
AssertionError
shell returned 1
我当然明白的,有在C(这是我说的错误)没有durp财产。不过,我不希望__getattr__
作为字符串使用hello来调用。我觉得我对__getattr__
的工作方式并不了解。
所以基本上C类创建一个AttributeError异常,因为在C中没有__getattr__它只是碰到没有得到“过时”而A会尝试处理它,因为有一个异常,即使它不是源于A类的,也是跛脚。似乎是一种奇怪的方式来确定“常用方法”失败,但这肯定会解释发生了什么。 – CrazyCasta 2014-12-03 07:26:07