E.g。
def __setattr__(self, name, value):
...
工作正常,但是:
def __init__(self):
self.__setattr__ = foo
似乎没有实现任何东西,因为永远不会调用foo。
提前致谢。
答案 0 :(得分:1)
__setattr__
使用类方法,而不是实例方法。检查以下代码的输出:
代码:
def func(*args):
print "--Func--"
print args
class A():
def __setattr__(*args):
print "--SetAttr--"
print args
a = A()
print "a.x = 10"
a.x = 10
print
A.__setattr__ = func
print "a.y = 20"
a.y = 20
print
输出:
a.x = 10
--SetAttr--
(<__main__.A instance at 0x2cb120>, 'x', 10)
a.y = 20
--Func--
(<__main__.A instance at 0x2cb120>, 'y', 20)
您可以编写代码,使类方法调用实例方法:
class C():
def __init__(self, setattr):
#Must access in this way since we overwrote __setattr__ already
self.__dict__['setattr_func'] = setattr
def __setattr__(self, name, value):
self.setattr_func(name, value)