Here is an example of what I am trying to achieve. The class has a someMethod
which has to be replaced with some other method (in this case returnStuff
) when instance is created. I am using lambda
to replace the method as the new one has an argument. Running the replaced method from a loop causes no problem, but running it after the loop turns all arguments to the same value. Replacing methods manualy works ok though. The code prints out everything needed to understand the problem.
def returnStuff(stuff):
return stuff
class SomeClass(object):
def __init__(self):
pass
def someMethod(self):
pass
classInstances = []
#RUN METHODS WITHIN CREATION LOOP
print 'STARTING CREATION LOOP:\n'
for i in range(1, 6):
classInstance = SomeClass()
classInstances.append(classInstance)
classInstance.someMethod = (lambda: returnStuff(i))
print 'I was returned from the Creation Loop and I am fabulous: ', classInstance.someMethod(), '\n'
print '====================================================================\n'
print 'RUN METHODS AFTER THE LOOP:\n'
#CALLING METHODS LATER ON
for inst in classInstances:
print 'I was returned after creation, and I am not who I want to be: ', inst.someMethod(), '\n'
print '====================================================================\n'
print 'TRYING MANUAL APPROACH (NO LOOP):\n'
classInstance1 = SomeClass()
classInstance1.someMethod = (lambda: returnStuff(1))
print 'I was returned from the manually replaced method. I\'m pretty fine: ', classInstance1.someMethod(), '\n'
classInstance2 = SomeClass()
classInstance2.someMethod = (lambda: returnStuff(2))
print 'I was returned from the manually replaced method. I\'m pretty fine: ', classInstance2.someMethod(), '\n'
classInstance3 = SomeClass()
classInstance3.someMethod = (lambda: returnStuff(3))
print 'I was returned from the manually replaced method. I\'m pretty fine: ', classInstance3.someMethod(), '\n'
classInstance4 = SomeClass()
classInstance4.someMethod = (lambda: returnStuff(4))
print 'I was returned from the manually replaced method. I\'m pretty fine: ', classInstance4.someMethod(), '\n'
classInstance5 = SomeClass()
classInstance5.someMethod = (lambda: returnStuff(5))
print 'I was returned from the manually replaced method. I\'m pretty fine: ', classInstance5.someMethod(), '\n'