Pit*_*kos 1 python namespaces function global-variables
我有一个嵌套在另一个函数中的函数。我想从嵌套函数中更改第一个函数内的变量。
def myfunc():
step=0
def increment():
step+=1
increment()
increment()
increment()
print("Steps so far:", step)
myfunc()
Run Code Online (Sandbox Code Playgroud)
给
UnboundLocalError:赋值前引用了局部变量“step”
如果我尝试使用global
,它也不会工作,因为它试图取消对step
外部myfunc
不存在的变量的引用。
有没有办法在没有全局变量的情况下做到这一点?
声明step
为nonlocal
变量。它将使标识符引用封闭范围内的变量。
def increment():
nonlocal step
step += 1
Run Code Online (Sandbox Code Playgroud)
注意仅限 Python 3.x。