Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning random value to a parameter in a python program

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.

like image 317
gmemon Avatar asked Jun 24 '11 02:06

gmemon


1 Answers

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
like image 197
Mark Ransom Avatar answered Sep 28 '22 02:09

Mark Ransom