我知道,在Python有可能在运行时的方法添加到类:覆盖在运行时__setattr__
class Test:
def __init__(self):
self.a=5
test=Test()
import types
def foo(self):
print self.a
test.foo = types.MethodType(foo, test)
test.foo() #prints 5
而且我也知道,它可能覆盖默认SETATTR类定义:
class Test:
def __init__(self):
self.a=5
def __setattr__(self,name,value):
print "Possibility disabled for the sake of this test"
test=Test() #prints the message from the custom method called inside __init__
然而,现在看来,这是不可能的,在运行时SETATTR覆盖:
class Test:
def __init__(self):
self.a=5
test=Test()
import types
def __setattr__(self,name,value):
print "Possibility disabled for the sake of this test"
test.__setattr__ = types.MethodType(__setattr__, test)
test.a=10 #does the assignment instead of calling the custom method
在最后两种情况下,dir(测试)还报告了方法setattr。但是,在第一种情况下,它正常工作,而在第二种情况下则不正确。请注意,我也可以明确地调用它,在这种情况下它可以工作。似乎是这样,虽然该方法已被定义,但尚未正确映射以覆盖默认分配方法。我错过了什么吗?
我正在使用Python 2.7。问题主要是学术问题,因为从程序设计的角度来看,做这样的事情可能不是一个好主意,但它仍然值得回答 - 尽管我搜索了,但我无法在任何地方找到它。
请注意,这明确地说“新风格的类”,而OP在他的示例中有一个旧式类 – lqc