__setattr__,如果存在,则为对象上设置的每个属性调用。
不过,您的示例代码让我很困惑。你想对声明做什么:
setattr(super(Clazz, self), name, value)??
在 self 上设置一个属性,将 self 视为其超类的一个实例?这是没有意义的,因为对象仍然是“自我”。
另一方面,尝试在调用“super”返回的对象上使用“setattr”总是会产生属性错误,无论该属性是否存在于超类中。那是因为 super 返回的不是超类本身,而是一个包装器对象,它会在需要时从那里获取属性 - 因此您可以在 super 返回的对象中使用“hasattr”,但不能使用 setattr。我以为它会这样,就在控制台上试了一下:
>>> 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)