4

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
asked Dec 21, 2014 at 1:55

1 Answer 1

6

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.

answered Dec 21, 2014 at 1:57
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.