2014-12-21 56 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

相关问题