__setattr__
,如果存在的话,被称为该对象上设置每个属性。
尽管如此,您的示例代码对我来说相当困惑。你想要做什么与声明: setattr(super(Clazz, self), name, value)
??
在self上设置一个属性,并将self视为其超类的一个实例?这没有意义,因为对象仍然是“自我”。
另一方面,试图对由“super”调用返回的对象使用“setattr”将始终产生属性错误,无论该属性是否存在于超类中。这是因为super不是超类本身,而是一个包装对象,它在需要的时候获取属性 - 所以你可以在由super返回的对象中使用“hasattr”,但不能在setattr中使用“hasattr”。我认为它会表现得如此,只是试了一下在控制台上:
>>> class A(object):pass
...
>>> class B(A): pass
...
>>> b = B()
>>> super(B,b)
<super: <class 'B'>, <B object>>
>>> setattr(super(B,b), "a", 5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'super' object has no attribute 'a'
>>> A.a = 1
>>> setattr(super(B,b), "a", 5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'super' object has no attribute 'a'
但是,你可以只使用“hasattr”的对象本身,然后像这样:
def __setattr__(self, attr, value):
if hasattr(self, value):
#this works because retrieving "__setattr__" from the
# result of the supercall gives the correct "__setattr__" of the superclass.
super(Clazz, self).__setattr__(self, attr, value)
else:
# transform value /or attribute as desired in your code
super(Clazz, self).__setattr__(self, attr, value)
那么,你可以使用'如果hasattr()'... – kindall 2012-02-03 18:14:36
那么,文档相当明确...还有什么要问? – delnan 2012-02-03 18:14:37
你可以让一个装饰器为你做 – jterrace 2012-02-03 18:17:26