Dynamically adding methods to objects?

damian birchler damian_birchler at bluewin.ch
Sun Jun 6 09:05:18 CEST 2004

Hello there!

I'm wondering if it is possible to automatically dynamically add
methods to a class instance. For example, if there is a class Foo with
one method named
add_function and an instance of Foo f -

class Foo:
   add_function(self, name, args):
      # ...
      # ...

f = Foo()

 -, could one add arbitrary methods to f calling its method

I know how to do it manually, I just define a function and assigne it
to f -

def bar():

f.bar = bar -,
but what if this should be done at runtime. How can I get the string
passed to f.add_function as name to be the name of a new function in
the function's definiton?

Thanks a lot

More information about the Python-list mailing list