gpt4 book ai didi

python - 用其中的另一个方法更改方法中的变量

转载 作者:IT老高 更新时间:2023-10-28 20:35:43 26 4
gpt4 key购买 nike

以下代码引发 UnboundLocalError:

def foo():
i = 0
def incr():
i += 1
incr()
print(i)

foo()

有没有办法做到这一点?

最佳答案

使用nonlocal语句

def foo():
i = 0
def incr():
nonlocal i
i += 1
incr()
print(i)

foo()

有关 python 3.x 中添加的这条新语句的更多信息,请访问 https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement

关于python - 用其中的另一个方法更改方法中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34431264/

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