yuan00yu 2019-06-27
最近开始学习python,一直觉得python定义变量前没有命令很难受,果然今天在练习闭包时遇到了这个问题。先看看出问题的代码
def createCounter():
n = 0
def counter():
n = n + 1
return n
return counter这里会报错:UnboundLocalError: local variable 'n' referenced before assignment
n = n + 1 这行代码导致的歧义新定义的变量n,并且n = n + 1,由于之前n未被定义,所以会报错def createCounter():
n = 0
def counter():
nonlocal n
n = n+1
return n
return counter这样子就不会报错了