我正在编写一个游戏,如果用户提供一个单词,游戏会使用该单词。否则,程序应该从字典中选择一个随机单词。 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) –
不,它不能。这是设计。默认值是在函数定义时计算的,而不是在函数调用时计算的。 –