这是我想要实现的一个例子。该类有一个someMethod
,在创建实例时必须用其他方法替换(在本例中为returnStuff
)。我使用lambda
替换方法,因为新方法有一个参数。从循环运行替换的方法没有问题,但在循环之后运行它将所有参数转换为相同的值。尽管如此,替换方法可以正常工作。代码打印出了解问题所需的一切。
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'
答案 0 :(得分:0)
而不是使用lambda(它没有为i
变量正确创建闭包)。你应该只使用部分或其他功能工厂。
E.g。
from functools import partial
for i in range(1, 6):
classInstance = SomeClass()
classInstances.append(classInstance)
classInstance.someMethod = partial(returnStuff, i)
或
def methodFactory(n):
def returnStuff():
return n
for i in range(1, 6):
classInstance = SomeClass()
classInstances.append(classInstance)
classInstance.someMethod = methodFactory(i)