Skip to main content
 首页 » 编程设计

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

2025年05月04日15zengkefu

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

类似的东西:

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

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

有一个 hacky 解决方案来制作列表并将该列表的第一个值用作 x。但这太丑了。

那么我如何共享 x 和 incx 函数呢?还是我应该使用完全不同的方法?

请您参考如下方法:

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

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

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