【问题标题】:How to make inner functions see variables of enclosing function? [duplicate]如何让内部函数看到封闭函数的变量? [复制]
【发布时间】:2011-12-20 15:35:07
【问题描述】:

可能重复:
Read/Write Python Closures

在下面的函数中,内部函数不修改参数,只是修改副本。

def func():
  i = 3
  def inc(i):
    i = i + 3
  print i
  inc(i)
  inc(i)
  print i

func()

是否可以避免重复代码并将其放入 python 的函数中?我也尝试了以下但它抛出错误UnboundLocalError: local variable 'i' referenced before assignment

def func():
  i = 3
  def inc():
    i = i + 3
  print i
  inc()
  inc()
  print i

func()

【问题讨论】:

标签: python


【解决方案1】:

在 python 3 中你会这样做:

def func():
  i = 3
  def inc():
    nonlocal i
    i = i+3
  print(i)
  inc()
  inc()
  print(i)

func()

在 python 2.x 中使用 global 不起作用,因为变量在外部范围内,但它不是全局的。因此,您需要将变量作为参数传递。

这是PEP 3104解决的问题。

【讨论】:

    【解决方案2】:

    怎么样:

    def func():
        i = 3
        def inc(i):
            return i + 3
        print i
        i = inc(i)
        i = inc(i)
        print i
    
    func()
    

    【讨论】:

      【解决方案3】:

      在 Python 3 中,您可以使用 nonlocal

      >>> def func():
          i = 3
          def inc():
              nonlocal i
              i += 3
          print(i)
          inc()
          inc()
          print(i)
      
      >>> func()
      3
      9
      >>> 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-04
        • 2017-02-25
        • 1970-01-01
        • 1970-01-01
        • 2012-04-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-27
        相关资源
        最近更新 更多