我知道在Python中可以在运行时向类添加一个方法:
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
Run Code Online (Sandbox Code Playgroud)
而且我也知道可以覆盖类定义中的默认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__
Run Code Online (Sandbox Code Playgroud)
但是,似乎无法在运行时覆盖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 …Run Code Online (Sandbox Code Playgroud) python ×1