dynamic function add to an instance of a class

James Mills prologic at shortcircuit.net.au
Thu Apr 29 04:12:44 EDT 2010


On Thu, Apr 29, 2010 at 5:55 PM, Richard Lamboj
<richard.lamboj at bilcom.at> wrote:
> i want to add functions to an instance of a class at runtime. The added
> function should contain a default parameter value. The function name and
> function default paramter values should be set dynamical.

The normal way of doing this by binding a new
MethodType to an instance:

>>> class A(object):
...     def foo(self):
...             return "foo"
...
>>> def bar(self):
...     return "bar"
...
>>> a = A()
>>> a.foo()
'foo'
>>> a.bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'bar'
>>> from types import MethodType
>>> setattr(a, "bar", MethodType(bar, a))
>>> a.bar()
'bar'
>>> a.foo
<bound method A.foo of <__main__.A object at 0x8380e8c>>
>>> a.bar
<bound method ?.bar of <__main__.A object at 0x8380e8c>>
>>>

cheers
James



More information about the Python-list mailing list