gpt4 book ai didi

python - python 中的嵌套范围

转载 作者:行者123 更新时间:2023-12-01 05:04:33 26 4
gpt4 key购买 nike

我的问题是关于封闭范围的规则。在下面的代码片段中,如果 x=x 没有传递到 F2 的 header ,则会出现错误

def f1():
x = 88
def f2(x=x): # Remember enclosing scope X with defaults
print(x)
f2()
f1()

但是我不明白为什么下面代码片段中的 lambda 不需要“x=x”

def func():
x = 4
action = (lambda n: x ** n) # x remembered from enclosing def
return action

x = func()
print(x(2))

最佳答案

In the snippet below if x=x is not passed to the header of F2 there will be an error

不,不会:

>>> def f1():
... x = 88
... def f2():
... print(x)
... f2()
...
>>> f1()
88
<小时/>

当您尝试传递稍后可能会更改的值时,您只需要修改默认参数值。 f2 正如我所写,它从封闭范围捕获变量 x ,因此它将打印当时发生的任何 x 。正如您所编写的,它捕获变量 x 的当前值,而不是变量本身。

例如:

>>> def f1():
... x = 88
... def f2():
... print(x)
... x = 44
... f2()
...
>>> f1()
44

>>> def f1():
... x = 88
... def f2(x=x):
... print(x)
... x = 44
... f2()
...
>>> f1()
88
<小时/>

有关这种差异重要性的现实生活中非常常见的示例,请参阅 Why do lambdas defined in a loop with different values all return the same result?在官方常见问题解答中。

关于python - python 中的嵌套范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25315683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com