Python 后期绑定问题
2019-03-28 本文已影响0人
tingshuo123
# test.py
def funs1():
return (lambda x: x+i for i in range(4))
def funs2():
return [lambda x: x+i for i in range(4)]
def funs3():
return [(lambda x, i=i: x+i) for i in range(4)]
if __name__ == "__main__":
print("fun1:")
for f in funs1():
print(f(0))
print("fun2:")
for f in funs2():
print(f(0))
print("fun3:")
for f in funs3():
print(f(0))
结果
# python3 test.py
fun1:
0
1
2
3
fun2:
3
3
3
3
fun3:
0
1
2
3