延迟绑定的问题
def create_multipliers():
return [lambda x : i * x for i in range(5)]
for multiplier in create_multipliers():
print(multiplier(2))
输出:
8
8
8
8
8
生成器解决办法
def create_multipliers():
for i in range(4):
yield lambda x : i * x
for multiplier in create_multipliers():
print(multiplier(2))
偏函数解决办法
from functools import partial
from operator import mul
def multipliers():
return [partial(mul, i) for i in range(4)]