Skip to content

Instantly share code, notes, and snippets.

@igorsobreira
Created March 5, 2010 18:38
Show Gist options
  • Save igorsobreira/323001 to your computer and use it in GitHub Desktop.
Save igorsobreira/323001 to your computer and use it in GitHub Desktop.
An way to add methods to an instance in Python
'''
An way to add methods to an instance.
>>> class Person(object):
... def __init__(self, name):
... self.name = name
...
>>> def upper_name(self):
... return self.name.upper()
...
>>> p = Person("Bob")
>>> p.name
'Bob'
# trying just add the function to an instance won't work if you plan to
# use ``self``
>>> p.upper_name = upper_name
>>> p.upper_name()
Traceback (most recent call last):
...
TypeError: upper_name() takes exactly 1 argument (0 given)
>>> add_instance_method(upper_name, p)
>>> p.upper_name()
'BOB'
'''
import types
def add_instance_method(function, instance):
method = types.MethodType(function, instance, instance.__class__)
setattr(instance, function.func_name, method)
if __name__ == '__main__':
import doctest
print doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment