最近开始学习python,一直以为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
这样子就不会报错了学习