2014-12-21 101 views
4

有沒有可能以任何方式將函數添加到類的現有實例? (最有可能只在當前交互式會話,當有人要添加一個方法,而不重新實例有用)在Python中創建一個類後添加一個方法

Example類:

class A(): 
    pass 

實例方法添加(引用自這裏重要):

def newMethod(self): 
    self.value = 1 

輸出:

>>> a = A() 
>>> a.newMethod = newMethod # this does not work unfortunately, not enough args 
TypeError: newMethod() takes exactly 1 argument (0 given) 
>>> a.value # so this is not existing 

回答

6

是的,但你需要馬nually結合它:

a.newMethod = newMethod.__get__(a, A) 

函數是descriptors並且當如在實例屬性擡頭通常結合到實例; Python然後調用.__get__方法來產生綁定方法。

演示:

>>> class A(): 
...  pass 
... 
>>> def newMethod(self): 
...  self.value = 1 
... 
>>> a = A() 
>>> newMethod 
<function newMethod at 0x106484848> 
>>> newMethod.__get__(a, A) 
<bound method A.newMethod of <__main__.A instance at 0x1082d1560>> 
>>> a.newMethod = newMethod.__get__(a, A) 
>>> a.newMethod() 
>>> a.value 
1 

不要顧及上的實例添加綁定方法確實產生循環引用,這意味着這些實例可以停留更久等待垃圾回收器來打破這個惡性循環,如果不再被引用由其他任何東西。

+0

儘快回覆,謝謝。 – PascalVKooten

相關問題