Adding a method to a class after it is created in Python

Is there any way to add a function to an existing instance of a class? (most likely only useful in the current interactive session, when someone wants to add a method without reinitializing)

Class Example:

class A():
    pass

An example of the add method (here the reference to self is important):

def newMethod(self):
    self.value = 1

Conclusion:

>>> 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
+4
source share
1 answer

Yes, but you need to manually bind it:

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

Functions are descriptors and are usually associated with instances when they look like instance attributes; Python then calls the method .__get__to create the associated method.

Demo:

>>> 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

, , , , , , .

+6

Source: https://habr.com/ru/post/1568496/


All Articles