Created
March 5, 2010 18:38
-
-
Save igorsobreira/323001 to your computer and use it in GitHub Desktop.
An way to add methods to an instance in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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