python - 传递 global 作为引用

标签 python function global-variables

我有类似的情况:

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/

相关文章:

python - Pandas 如何在将 DataFrame 导出为 CSV 时保留最后一个尾随零

python - pandas:将函数应用于数据框列中的每个唯一元素并合并回输出

python - Django 中意外的日期时间格式

iphone - 如何使用临时变量在 Objective-C/Xcode 中定义返回的 NSString 函数?

javascript - 带参数的调用函数和带其他参数返回值的调用函数有什么区别

c# - 我可以在我的 C# 程序中的什么地方使用全局变量?

python - PyQtGraph : how to change size (height and width) of graph in a ScrollArea

javascript - 在变量中声明一个 JavaScript 函数?

lua - 跨 Lua 状态复制全局表

javascript - 如何访问输入标签值