Dynamically adding methods to objects?

Robert Brewer fumanchu at amor.org
Sun Jun 6 09:54:33 CEST 2004


damian birchler wrote:
> 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
> add_function?
> 
> I know how to do it manually, I just define a function and assigne it
> to f -
> 
> def bar():
>   pass
> 
> 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?

Yes, it is possible. Have a look at new.instancemethod:

http://docs.python.org/lib/module-new.html

Then hop over to the Python Cookbook for implementations:

http://aspn.activestate.com/ASPN/Python/Cookbook/


HTH!

FuManChu





More information about the Python-list mailing list