Python 仅为函数内部的函数共享全局变量

Python share global variable only for functions inside of function

我有一个函数,它将在内部递归执行另一个函数,我想为该函数的所有执行共享变量。

类似的东西:

def testglobal():
  x = 0
  def incx():
    global x
    x += 2
  incx()
  return x
testglobal() # should return 2

但是,我遇到了错误 NameError: name 'x' is not defined

创建列表并使用该列表的第一个值作为 x 的 hacky 解决方案。但这太丑了。

那么我怎样才能将 xincx 功能共享?或者我应该使用完全不同的方法?

您想使用 nonlocal 语句访问 x,它不是全局的,而是 testglobal 的本地。

def testglobal():
  x = 0
  def incx():
    nonlocal x
    x += 2
  incx()
  return x
assert 2 == testglobal() 

您在 Python 2 中最接近的做法是将 x 替换为可变值,类似于您在问题中提到的参数 hack。

def testglobal():
  x = [0]
  def incx():
    x[0] += 2
  incx()
  return x[0]
assert 2 == testglobal()

这是一个使用函数属性而不是列表的示例,您可能会发现这种替代方法更有吸引力。

def testglobal():
  def incx():
    incx.x += 2
  incx.x = 0
  incx()
  return inc.x
assert 2 == testglobal() 

这将有效,除非您仍在使用 Python 2.x:

def testglobal():
  x = 0
  def incx():
    nonlocal x
    x += 2
  incx()
  return x

testglobal() # should return 2

可能更简洁的解决方案是定义一个 class 来存储方法调用之间的状态。

使用 nonlocal 语句,因此 incx 将使用 testglobal:

中的 x 变量
def testglobal():
    x = 0
    def incx():
        nonlocal x
        x += 2
    incx()
    return x

testglobal()