gpt4 book ai didi

python - 另一个 Python 变量范围问题

转载 作者:行者123 更新时间:2023-11-28 20:52:47 25 4
gpt4 key购买 nike

我有以下代码:

>>> def f(v=1):
... def ff():
... print v
... v = 2
... ff()
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in f
File "<stdin>", line 3, in ff
UnboundLocalError: local variable 'v' referenced before assignment

我明白为什么会出现此消息 ( Python variable scope question ),但在这种情况下我如何使用 v 变量? global v 在这种情况下不起作用。

最佳答案

在 Python 3.x 中,您可以使用 nonlocal :

def f(v=1):
def ff():
nonlocal v
print(v)
v = 2
ff()

在 Python 2.x 中,没有简单的解决方案。一个 hack 是使 v 成为一个列表:

def f(v=None):
if v is None:
v = [1]
def ff():
print v[0]
v[0] = 2
ff()

关于python - 另一个 Python 变量范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6256537/

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