Python中的奇怪的闭包行为 [英] Weird closure behavior in python

查看:115
本文介绍了Python中的奇怪的闭包行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单代码:

def get():
    return [lambda: i for i in [1, 2, 3]]

for f in get():
    print(f())

根据我的python知识,输出为3 - 整个列表将包含 i 的最后一个值。但这如何在内部工作?

As expected from my python knowledge, output is 3 - entire list will contain last value of i. But how this works internally?

AFAIK,python变量只是引用对象,因此第一个闭包必须包含对象第一 i 对象肯定是1,而不是3 O_O。如何发生,python闭包括变量本身,而不是对象这个变量引用?是否将变量名保存为纯文本,一些引用变量或什么?

AFAIK, python variables are simply reference to objects, so first closure must enclose object first i reference - and this object is definitely 1, not 3 O_O. How it happens that python closure encloses variable itself instead of object this variable reference? Does it save variable name as plain text, some "reference to variable" or what?

推荐答案

em>变量,而是范围。由于其范围中的 i 的最后一个值为'3',所有三个闭包都返回相同。要锁定变量的当前值,请为其创建一个新范围:

Closures don't refer to variables but rather to scopes. Since the last value of i in its scope is '3', all three closures return the same. To "lock" the current value of a variable, create a new scope just for it:

def get() : return [ (lambda x: lambda: x)(i) for i in [ 1, 2, 3 ] ]
for f in get() : print( f() )

这篇关于Python中的奇怪的闭包行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆