将随机值分配给python程序中的参数

gme*_*mon 5 python random parameters init

我需要在中分配默认随机值__init__().例如:

import math
import random
class Test:
    def __init__(self, r = random.randrange(0, math.pow(2,128)-1)):
        self.r = r
        print self.r
Run Code Online (Sandbox Code Playgroud)

如果我创建了10个Test实例,它们都会获得完全相同的随机值.我不明白为什么会这样.我知道我可以在其中分配随机值__init__(),但我很好奇为什么会发生这种情况.我的第一个猜测是种子是当前时间,并且对象的创建距离太近,因此获得相同的随机值.我创建的对象间隔1秒,但结果仍然相同.

Mar*_*som 15

默认参数的值是在创建函数时设置的,而不是在调用函数时设置的 - 这就是每次都相同的原因.

处理此问题的典型方法是将默认参数设置为None并使用if语句对其进行测试.

import math
import random
class Test:
     def __init__(self, r = None):
             if r is None:
                 r = random.randrange(0, math.pow(2,128)-1)
             self.r = r
             print self.r
Run Code Online (Sandbox Code Playgroud)


Rou*_*wer 5

random.randrange(0, math.pow(2,128)-1)定义函数时计算 ,而不是在调用时计算。

class Test:
    def __init__(self, r = None):
        if r is None:
            r = random.randrange(0, math.pow(2,128)-1)
        self.r = r
        print self.r
Run Code Online (Sandbox Code Playgroud)

反而。