Reputation: 21443
Would it be possible in any way to add a function to an existing instance of a class? (most likely only useful in a current interactive session, when someone wants to add a method without reinstantiating)
Example class:
class A():
pass
Example method to add (the reference to self is important here):
def newMethod(self):
self.value = 1
Output:
>>> 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
Upvotes: 4
Views: 161
Reputation: 1121634
Yes, but you need to manually bind it:
a.newMethod = newMethod.__get__(a, A)
Functions are descriptors and are normally bound to instances when looked up as attributes on the instance; Python then calls the .__get__
method for you to produce the bound 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
Do take into account that adding bound methods on instances does create circular references, which means that these instances can stay around longer waiting for the garbage collector to break the cycle if no longer referenced by anything else.
Upvotes: 6