Skip to content

Instantly share code, notes, and snippets.

@alexbowe
Created March 28, 2010 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexbowe/346711 to your computer and use it in GitHub Desktop.
Save alexbowe/346711 to your computer and use it in GitHub Desktop.
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())
example:
def func(self):
print 'test'
add_method(myObject, func, 'newmethodname')
myObject.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