Dynamically adding methods to objects?

Leif K-Brooks eurleif at ecritters.biz
Mon Jun 7 04:58:09 CEST 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.

         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.")

More information about the Python-list mailing list