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)