我在分配赋值运算符时遇到问题。
我已经成功重载__setattr__
。但是在对象初始化之后,我想做__setattr__
点别的,所以我尝试将它分配给另一个函数,__setattr2__
.
代码:
class C(object):
def __init__(self):
self.x = 0
self.__setattr__ = self.__setattr2__
def __setattr__(self, name, value):
print "first, setting", name
object.__setattr__(self, name, value)
def __setattr2__(self, name, value):
print "second, setting", name
object.__setattr__(self, name, value)
c = C()
c.x = 1
我得到什么:
first, setting x
first, setting __setattr__
first, setting x
我想要/期望的:
first, setting x
first, setting __setattr__
second, setting x