'bind' functions into methods

TeaAndBikkie teaandbikkie at aol.com
Sun Oct 20 10:44:40 EDT 2002


>On Sun, Oct 20, 2002 at 12:04:15AM +0000, TeaAndBikkie wrote:
>> I have a set of functions, op1(), op2(), etc. with initial argument 'n' the
>> same.
>> 
>> I want to "bind" them into a class as methods that pass the first argument
>from
>> an instance variable.

Thanks for your responses Oren and Jeff, with your help I have worked out a
nice solution.

Oren, your answer is nice and elegant, and does what I asked nicely.
An additional requirement I forgot to mention :) is that the value
of the first argument may change as the instance variable changes...

Jeff, after wrapping my head around your code I think I now understand
what is going on. At first I tried a lambda inside a loop with setattr:

funcs = (op1, op2)
for f in funcs:
    setattr(self, f.func_name, lambda *args, **kw: f(self.n, *args, **kw))

but calling method op1 invoked function op2, so I guess the 'f' in the lambda
is being evaluated on the lambda call, rather than at definition (makes some
sense).

After some mucking around, I put in a wrapper as you suggest, and it works
well:

class tobj:
    def __init__(self, n=None):
        self.n = n
        funcs = (op1, op2)
        for f in funcs:
            setattr(self, f.func_name, self._wrapper(f))

    def _wrapper(self, f):
        return lambda *args, **kw: f(self.n, *args, **kw)

I think this works because the 'f' in _wrapper() is a copy of the 'f' passed
in from the for loop, and the lambda uses the copy rather than the value of 'f'
at the time of the call.

Kind regards,
Misha




More information about the Python-list mailing list