Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么我可以覆盖'__setattr__#x27;但不在_init__方法中分配它?_Python_Python 2.7 - Fatal编程技术网

Python 为什么我可以覆盖'__setattr__#x27;但不在_init__方法中分配它?

Python 为什么我可以覆盖'__setattr__#x27;但不在_init__方法中分配它?,python,python-2.7,Python,Python 2.7,例如 工作正常,但是: def __setattr__(self, name, value): ... 似乎什么都没有,因为foo从来没有被调用过 提前感谢。\uuuu setattr\uuuu使用类方法,而不是实例方法。检查以下代码的输出: 代码: 输出: def func(*args): print "--Func--" print args class A(): def __setattr__(*args): print "--SetAt

例如

工作正常,但是:

def __setattr__(self, name, value):
    ...
似乎什么都没有,因为foo从来没有被调用过


提前感谢。

\uuuu setattr\uuuu
使用类方法,而不是实例方法。检查以下代码的输出:

代码:

输出:

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

起点:
\uuuu setattr\uuuu
在类上查找,而不是在实例上。
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)