Dynamically adding methods to objects?

Leif K-Brooks eurleif at ecritters.biz
Sun Jun 6 22:58:09 EDT 2004


damian birchler wrote:
> I'm wondering if it is possible to automatically dynamically add
> methods to a class instance.

Try something like this:

import new

class Foo(object):
     def add_method(self, name, prints):
         """Add a method to the class which prints a string.

         Arguments:
         name - the name of the method
         prints - the string the method should print
         """
         def method(self):
             print prints

         method = new.instancemethod(method, self, Foo)
         setattr(self, name, method)

instance = Foo()
instance.add_method('foo', 'I am foo. Fear me!')
instance.add_method('bar', "I am the humble bar. Please don't hurt me.")
instance.foo()
instance.bar()



More information about the Python-list mailing list