嵌套函数中的奇怪范围

时间:2017-03-20 08:47:54

标签: python scope nested-function

我有两个嵌套的python函数,如下所示:

def outer():
  t = 0
  def inner():
    t += 1
    print(t)
  inner()

尝试拨打outer会导致以下错误:

>>> outer()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "sally.py", line 6, in outer
    inner()
  File "sally.py", line 4, in inner
    t += 1
UnboundLocalError: local variable 't' referenced before assignment

我认为在global t之前添加行t += 1会有所帮助,但事实并非如此。

为什么会这样?除了每次调用它时都将t传递给inner,我该如何解决这个问题呢?

1 个答案:

答案 0 :(得分:3)

如果使用python 3,那么使用nonlocal关键字会让解释器知道使用outer()函数的范围来表示t:

def outer():
  t = 0
  def inner():
    nonlocal t
    t += 1
    print(t)
  inner()


如果使用python 2,则不能直接赋值给变量,否则会使解释器创建一个新的变量t,它将隐藏外部变量。您可以传入可变集合并更新第一项:

def outer():
  t = [0]
  def inner():
    t[0] += 1
    print(t[0])
  inner()