python-3.x - Python 的 lambda 函数中的无效闭包
问题描述
考虑这个简短的代码片段:
class X:
pass
xs = []
for s in ("one", "two", "three"):
x = X()
x.f = lambda: print(s)
xs.append(x)
for x in xs:
x.f()
它输出:
three
three
three
这真的是预期的行为吗?你能解释为什么这不是:
one
two
three
解决方案
您的 lambda 函数持有对 的引用s
,因此在该 for 循环之外调用时会打印最后分配给 s 的值。尝试以下代码以获得您的预期行为。在这里,现有引用的副本作为函数参数s
创建,v
并且该值在函数内部打印f
。
class X:
pass
xs = []
for s in ("one", "two", "three"):
x = X()
def f(v=s): print(v)
x.f = f
xs.append(x)
for x in xs:
x.f()
输出:
one
two
three
推荐阅读
- c# - C# 将文件夹中的最后一个文件复制到另一个生成的文件夹中
- python - 通过设置或 Python LibVLC API 对 VLC 网络流中的自动重新连接失败进行故障排除
- html - div标签中的背景图像大小 - 全屏 - 内联css
- android - 如何检查应用程序是否使用 jni 安装?
- ajax - 阿贾克斯和 Django
- java - 如何在不使用数组的情况下更改 showConfirmDialog 中的文本?
- reactjs - 如何从 Redux store 中删除 Board-React js,redux
- javascript - PHP 联系表格未收到电子邮件但已确认
- anaconda - 在 Anaconda 问题上安装 pymzml
- javascript - 由于 ble.scan 的异步执行,基于设备名称的 Cordova BLE Connect 自动(无需用户操作)失败