Dynamically adding methods to objects?
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
> 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?
Yes, it is possible. Have a look at new.instancemethod:
Then hop over to the Python Cookbook for implementations:
More information about the Python-list