我有类似的情况:
x = 10
y = 20
z = 30
def check_x():
global x
if something:
x = x + 10
def check_y():
global y
if something:
y = y + 15
def check_z():
global z
if something:
z = z + 20
为了出现这种情况,我怎样才能实现重构:
x = 10
y = 20
z = 30
def check(var, adding):
global ??
if something:
?? = ?? + adding
check(x, 10)
check(y, 15)
check(z, 20)
基本上,我不能在通用函数中引用给定的全局变量。
最佳答案
您可以访问 globals()
dict,并传递一个 str 作为参数:
>>> x = 10
>>> def check_x(glb, adding):
if glb in globals():
globals()[glb] += adding
>>> check_x('x', 10)
>>> x
20
关于python - 传递 global 作为引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65884525/