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

像这样:

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


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

有一个骇人的解决方案可以创建列表并将该列表的第一个值用作x。但这太丑了。

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

最佳答案

您想使用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 - Python仅对函数内部的函数共享全局变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39663207/

10-10 20:44
查看更多