在Python中创建一个类后,将该方法添加到类中

Pas*_*ten 4 python class

是否可以以任何方式将函数添加到类的现有实例中?(最有可能仅在当前的交互式会话中有用,当有人想要添加方法而不重新实例化时)

示例类:

class A():
    pass
Run Code Online (Sandbox Code Playgroud)

添加的示例方法(对self的引用在这里很重要):

def newMethod(self):
    self.value = 1
Run Code Online (Sandbox Code Playgroud)

输出:

>>> 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
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

是的,但您需要手动绑定它:

a.newMethod = newMethod.__get__(a, A)
Run Code Online (Sandbox Code Playgroud)

函数是描述符,通常在实例上作为属性查找时绑定到实例; 然后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
Run Code Online (Sandbox Code Playgroud)

请注意,在实例上添加绑定方法会创建循环引用,这意味着这些实例可以保持更长时间,等待垃圾收集器在不再被其他任何内容引用时中断循环.