2017-05-26 30 views
0

首先,爲標題道歉,我想不出一個更好的。我想要做的是能夠減少我的代碼中if語句的數量。 這裏是我的代碼:Python 3.6 - 寫入隨機變量

if var is "forwardThrustButton": 
    global forwardThrustButton 
    forwardThrustButton = res 
elif var is "backThrustButton": 
    global backThrustButton 
    backThrustButton = res 
elif var is "leftRotateButton": 
    global leftRotateButton 
    leftRotateButton = res 
elif var is "rightRotateButton": 
    global rightRotateButton 
    rightRotateButton = res 
elif var is "basicShootButton": 
    global basicShootButton 
    basicShootButton = res 
elif var is "specialShootButton": 
    global specialShootButton 
    specialShootButton = res 
elif var is "bombShootButton": 
    global bombShootButton 
    bombShootButton = res 

正如你可以看到我有很多的if語句在這裏,用我所投入的函數的字符串,並檢查,看看該字符串是什麼。此代碼有效。我想要做的是能夠將一個變量的名稱傳遞給函數,並且只是說var = res。提前致謝。

+6

請勿使用動態變量,請使用字典。 –

+0

你能解釋一下爲什麼*你需要一個單獨的變量取決於另一個變量?這種方法導致的問題是,您永遠不知道在某個時間點存在哪些變量。正如@ juanpa.arrivillaga所說:使用字典。看看這裏:https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables –

+0

比較字符串與'is'是一個壞主意:https:// stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce –

回答

1

你可以試試:

​​

locals()[var] = res 

取決於範圍上下文。但這很醜陋,最好使用字典。

1

如果你只是擁有所有這些按鈕值的字典,那麼你可以很容易地只說

buttons["leftRotateButton"] = res 

,將清理你的代碼各地也

buttons[var] = res 
0

首先,使用==代替isis是一種身份的測試,你基本上是檢查是否var"forwardThrustButton",同樣的str實例。此檢查的結果取決於特定Python版本的字符串實施。您可以檢查theseposts以獲取有關該主題的更多信息。
除此之外,你可以保留一個dict所有可能的按鈕名稱作爲按鍵和按鈕的值,如前所述,或使用exec("global " + var + "; " + var + " = res"),雖然後者是相當醜陋的(但完成工作)。