'bind' functions into methods

TeaAndBikkie teaandbikkie at aol.com
Sat Oct 19 20:04:15 EDT 2002


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.

So far I have the following, but is there a better way to do this?
Can I generate the methods op1, op2, etc. by looping through a list of
functions?
Can I put some shared code for every method call (eg. to check if n is None)?

Kind regards,
Misha

... sample code, on Python 2.2.1 ...

def op1(n, dude):
    print "[[[%d -> %d]]]" % (n, dude)

def op2(n, eric, fish):
    print "[[[%d -> %d :: %d]]]" % (n, eric, fish)

class tobj:
    def __init__(self, n=None):
        self.n = n
    def op1(self, *arg, **kwargs):
        return op1(self.n, *arg, **kwargs)
    def op2(self, *arg, **kwargs):
        return op2(self.n, *arg, **kwargs)

# sample usage...

op1(6, 8)
#[[[6 -> 8]]]

op2(6, 3, 9)
#[[[6 -> 3 :: 9]]]

a=tobj(6)
a.op1(dude=8)
#[[[6 -> 8]]]

a.op2(fish=9,eric=3)
#[[[6 -> 3 :: 9]]]

b=tobj()
b.n=7
b.op1(8)
#[[[7 -> 8]]]




More information about the Python-list mailing list