2

例如

def __setattr__(self, name, value):
    ...

工作正常,但是:

def __init__(self):
    self.__setattr__ = foo

从来没有调用 foo 似乎没有取得任何成就。

提前致谢。

4

1 回答 1

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)
于 2013-08-25T20:00:49.767 回答