【发布时间】:2019-05-17 07:19:56
【问题描述】:
我遇到了这样一个面试问题:
说出下面sn-p的输出:
def num():
return [lambda x:i*x for i in range(4)]
print([m(2)for m in num()])
我觉得很简单,猜到了[0, 2, 4, 6]
不幸的是
In [1]: def num():
...: return [lambda x:i*x for i in range(4)]
In [2]: print([m(2) for m in num()])
[6, 6, 6, 6]
查看其详细信息
In [5]: for _ in num():
...: print(_)
...:
<function num.<locals>.<listcomp>.<lambda> at 0x7f042411dc80>
<function num.<locals>.<listcomp>.<lambda> at 0x7f0424182378>
<function num.<locals>.<listcomp>.<lambda> at 0x7f04240dfc80>
<function num.<locals>.<listcomp>.<lambda> at 0x7f042410ed08>
这样一个晦涩难懂的语法叫什么来定义一个num,
怎么会输出[6, 6, 6,6]这样的结果
我看了python - Lambdas inside list comprehensions - Stack Overflow
>>> y = 3
>>> f = lambda: y
>>> f()
3
>>> y = 4
>>> f()
4
用标准的方式表达
In [15]: def foo(): return x
In [16]: x = 1; foo()
Out[16]: 1
In [17]: x = 4; foo()
Out[17]: 4
没有说明关闭的解释是不可想象的。
维基百科的答案最好将其视为对影子变量的闭包的模糊用法
这也可以通过变量遮蔽(减少非局部变量的范围)来实现,尽管这在实践中不太常见,因为它不太有用并且不鼓励使用遮蔽。在这个例子中 f 可以看作是一个闭包,因为 f 主体中的 x 绑定到全局命名空间中的 x,而不是 g 本地的 x:
Closure (computer programming) - Wikipedia
x = 0
def f(y):
return x + y
def g(z):
x = 1 # local x shadows global x
return f(z)
g(1) # evaluates to 1, not 2
【问题讨论】:
标签: python python-3.x lambda