Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python function for adding an instance method to an object
def add_method(obj, f, fname):
"""Adds the instance method from function f to the object obj, callable by fname (i.e. obj.fname())
def func(self):
print 'test'
add_method(myObject, func, 'newmethodname')
from new import instancemethod
obj.__dict__[fname] = instancemethod(f, obj, obj.__class__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment