逸思杂陈

逸思杂陈

马上订阅 逸思杂陈 RSS 更新: https://blog.ponder.work/atom.xml

Python 循环变量泄露与延迟绑定

2022年3月4日 20:17

循环变量泄露与延迟绑定叠加在一起,会产生一些让人迷惑的结果。

梦开始的地方

先看看一开始的问题,可以看到这里lambda函数的返回值一直在变。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
xx = []
for i in [1,2,3]:
xx.append(lambda: i)

print('a:', xx[0]())

for j in xx:
print(j())

print('b:', xx[0]())

for i in xx:
print(i, i())

print('c:', xx[0], xx[0]())

for i in [4, 5, 6]:
print(i)

print('d:', xx[0], xx[0]())

输出如下

1
2
3
4
5
6
7
8
9
10
11
12
13
a: 3
3
3
3
b: 3
<function main2.<locals>.<lambda> at 0x10ca30310> <function main2.<locals>.<lambda> at 0x10ca30310>
<function main2.<locals>.<lambda> at 0x10ca303a0> <function main2.<locals>.<lambda> at 0x10ca303a0>
<function main2.<locals>.<lambda> at 0x10ca30430> <function main2.<locals>.<lambda> at 0x10ca30430>
c: <function main2.<locals>.<lambda> at 0x10ca30310> <function main2.<locals>.<lambda> at 0x10ca30430>
4
5
6
d: <function main2.<locals>.<lambda> at 0x10ca30310> 6

循环变量泄露

由于Python没有块级作用域,所以循环会改变当前作用域变量的值,也就是循环变量泄露。
注意:Python3中列表推导式循环变量不会泄露,Python2中和常规循环一样泄露。

1
2
3
4
5
x = -1
for x in range(7):...

剩余内容已隐藏

查看完整文章以阅读更多