how do you use a closure in a class

Paul McGuire ptmcg at austin.rr.com
Wed Mar 30 09:40:52 EST 2005


See the following.
-- Paul

class X(object):
....pass

def makeAddr(tAdd):
....def add(self, tNum):
........return tNum + tAdd
....return add

# add methods to class X
X.add1 = makeAddr(1)
X.add100 = makeAddr(100)

# create an X object
x = X()

# invoke new methods
print x.add1( 50 )
print x.add100( 50 )

Prints:
51
150




More information about the Python-list mailing list