【发布时间】:2014-11-05 11:38:32
【问题描述】:
我有一个嵌套在另一个函数中的函数。我想从嵌套的函数中更改第一个函数中的变量。
def myfunc():
step=0
def increment():
step+=1
increment()
increment()
increment()
print("Steps so far:", step)
myfunc()
给予
UnboundLocalError:赋值前引用了局部变量“step”
如果我尝试使用global,它也不会工作,因为它会尝试取消引用myfunc 之外不存在的变量step。
有没有办法在没有全局变量的情况下做到这一点?
【问题讨论】:
标签: python function namespaces global-variables