简体   繁体   English

Python - 更改函数参数,即使它是全局的

[英]Python - Change a function parameter even if it's global

I've made a function that I want to use to change a variable, this variable also happens to be global.我已经创建了一个函数,我想用它来更改一个变量,这个变量也恰好是全局的。

def CheckMarkFunc(var):
    if var == True:
        var= False
    elif var == False:
        var= True

If var is a global, it wont change.如果 var 是一个全局变量,它不会改变。 Is there a way to change the var without having to hardcode the global parameter (sound_mute, in this case) into the function itself?有没有办法改变 var 而不必将全局参数(在本例中为 sound_mute)硬编码到函数本身中?

The code below works, but I'd rather not have multiple if statements for each global variable that I want to change, if at all possible:下面的代码有效,但如果可能的话,我宁愿不要为我想要更改的每个全局变量设置多个 if 语句:

def CheckMarkFunc(var,button_id,uncheck_texture,checked_texture):
    global sound_mute
    if var == True:
        TextureSwap(uncheck_texture,button_id)
        sound_mute = False
    if var == False:
        sound_mute = True
        TextureSwap(checked_texture,button_id)

In both of these cases, the var parameter is the sound_mute boolean.在这两种情况下,var 参数都是sound_mute布尔值。

One option is as follows:一种选择如下:

def CheckMarkFunc(var, button_id, uncheck_texture, checked_texture):
    if var:
        TextureSwap(uncheck_texture, button_id)
    else:
        TextureSwap(checked_texture, button_id)

    return not var

sound_mute = CheckMarkFunc(sound_mute, button_id, uncheck_texture, checked_texture)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM