我刚刚发现这个奇怪的Python'bug',我想知道是否有人知道更多!
比如拿python模块:
import random
class SaySomething:
def __init__(self, value=random.randint(1, 3)):
if value == 1: print 'one'
elif value == 2: print 'two'
elif value == 3: print 'three'
a = 0
while a < 10:
SaySomething()
a += 1
Run Code Online (Sandbox Code Playgroud)
此代码由于某种原因将打印相同的10次号码!!! 现在这个我不明白.似乎连续10次使用相同的值调用构造函数.但是如果你打印每个SaySomething()都会看到它们都有不同的指针地址,所以它们不是同一个对象.
现在,如果你改变:
SaySomething()
Run Code Online (Sandbox Code Playgroud)
至
SaySomething(random.randint(1, 3))
Run Code Online (Sandbox Code Playgroud)
它按预期运行,并进行实际的随机选择.
谁知道为什么会这样?
Ale*_*kiy 13
问题是,在创建函数时,Python中的默认参数将被计算一次.要解决此问题,请尝试:
def __init__(self, value = None):
if value is None:
value = random.randint(1, 3)
if value == 1: print 'one'
elif value == 2: print 'two'
elif value == 3: print 'three'
Run Code Online (Sandbox Code Playgroud)
这样,我们将随机化转移到函数本身,而不是在函数定义时.