Re: dynamic function add to an instance of a class
- From: Peter Otten <__peter__@xxxxxx>
- Date: Thu, 29 Apr 2010 10:43:38 +0200
News123 wrote:
Peter Otten wrote:
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.
... def __init__(self, x):class A(object):
... self.x = x
... def m(self):
... return self.f(self.x)
...
... return self.x + a**ba = A(42)
def foo(self, a, b):
...
109418989131512359251Lfrom functools import partial
a.f = partial(foo, a, 3)
a.m()
True42 + 3**42 == _
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 drawback would be, that
the call
a.f()
will not automagically pass self as the first argument.
b = A(123)
b.f()
would still be called with a as bound object.
There is no b.f until you explicitly assign it with
b.f = f
If you want the function to work uniformly across all instances of the class
you are better off with adding it to the class
def f(self, x, y):
...
A.f = f
However, if you want x to have a fixed value -- that is beyond the
capabilities of functols partial. You have to wrap f in another function:
A.f = lambda self, y: f(self, 42, y)
Peter
.
- Follow-Ups:
- Re: dynamic function add to an instance of a class
- From: News123
- Re: dynamic function add to an instance of a class
- References:
- dynamic function add to an instance of a class
- From: Richard Lamboj
- Re: dynamic function add to an instance of a class
- From: Peter Otten
- Re: dynamic function add to an instance of a class
- From: News123
- dynamic function add to an instance of a class
- Prev by Date: Re: printing table on the command line
- Next by Date: Re: dynamic function add to an instance of a class
- Previous by thread: Re: dynamic function add to an instance of a class
- Next by thread: Re: dynamic function add to an instance of a class
- Index(es):
Relevant Pages
|