[英]Python - Change a function parameter even if it's global
我已經創建了一個函數,我想用它來更改一個變量,這個變量也恰好是全局的。
def CheckMarkFunc(var):
if var == True:
var= False
elif var == False:
var= True
如果 var 是一個全局變量,它不會改變。 有沒有辦法改變 var 而不必將全局參數(在本例中為 sound_mute)硬編碼到函數本身中?
下面的代碼有效,但如果可能的話,我寧願不要為我想要更改的每個全局變量設置多個 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)
在這兩種情況下,var 參數都是sound_mute
布爾值。
一種選擇如下:
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.