I need to assign a default random value in __init__()
. For example:
import math
import random
class Test:
def __init__(self, r = random.randrange(0, math.pow(2,128)-1)):
self.r = r
print self.r
If I create 10 instances of Test, they all get the exact same random value. I don't understand why this is happening. I know I can assign the random value inside the __init__()
, but I am curious why this is happening. My first guess was that the seed is the current time and objects are being created too close together, and, as a result, get the same random value. I created objects 1 second apart, but still same result.
The value of the default parameter is being set at the time the function is created, not when it is called - that's why it's the same every time.
The typical way to deal with this is to set the default parameter to None
and test it with an if
statement.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With