gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:15 28 4
gpt4 key购买 nike

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

类似的东西:

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。但这太丑了。

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

最佳答案

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

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

testglobal() # should return 2

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

关于Python 只为函数内部的函数共享全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39663207/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com