我正在編寫一個遊戲,如果用戶提供一個單詞,遊戲會使用該單詞。否則,程序應該從字典中選擇一個隨機單詞。 Dictionary是一個全球列表。目前,默認的隨機數將始終評估爲0,但在其他地方正確評估。Python - len(x)不參數評估?
代碼:
def game(i = random.randint(0, len(dictionary))):
print 'default random:', i
print 'random inside function:', random.randint(0, len(dictionary))
輸出:
default random: 0
random inside function: 40403
能蟒蛇不能評價len個內部參數?
它可以,但你應該真的把應用程序邏輯內的功能,而不是它的簽名。 –
[「Python中最小的驚訝」可能的重複:可變的默認參數](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument) –
不,它不能。這是設計。默認值是在函數定義時計算的,而不是在函數調用時計算的。 –