我知道,在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