简体   繁体   中英

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. Is there a way to change the var without having to hardcode the global parameter (sound_mute, in this case) into the function itself?

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:

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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