dynamic function add to an instance of a class

Richard Lamboj richard.lamboj at bilcom.at
Thu Apr 29 04:44:54 EDT 2010


Am Thursday 29 April 2010 10:13:01 schrieb Peter Otten:
> Richard Lamboj 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.
> >
> >>> class A(object):
>
> ...     def __init__(self, x):
> ...             self.x = x
> ...     def m(self):
> ...             return self.f(self.x)
> ...
>
> >>> a = A(42)
> >>>
> >>> def foo(self, a, b):
>
> ...     return self.x + a**b
> ...
>
> >>> from functools import partial
> >>> a.f = partial(foo, a, 3)
> >>> a.m()
>
> 109418989131512359251L
>
> >>> 42 + 3**42 == _
>
> True
>
> Confused? The important points are
>
> (1)
>
> functools.partial(f, a1, a2, a3, ...)(b1, b2, b3, ...)
>
> is equivalent to
>
> f(a1, a2, a3, ..., b1, b2, b3, ...)
>
> (2)
>
> If you stick a function into an instance
>
> a.f = f
>
> the call
>
> a.f()
>
> will not automagically pass self as the first argument.
>
> Peter

Thats what i want:

from functools import partial

class A(object):
	def add_function(self, function_name, value):
		setattr(self, function_name, partial(self.test, value))
		
	def test(self, value):
		print value
		
	
a = A()
a.add_function("func1", "value1")
a.func1()

Thanks to all for helping me!

Kind Regard,

Richi



More information about the Python-list mailing list