[Tutor] generating independent random numbers

Steven D'Aprano steve at pearwood.info
Tue Sep 28 02:27:07 CEST 2010


On Tue, 28 Sep 2010 08:55:36 am Carter Danforth wrote:

> class Date:
>     c = random.randint(16,30)
>     y = random.randint(0,99)
>     month = random.randint(1,12)

Here's your problem: you are creating a class where all the attributes 
(called "members" in some other languages) belong to the class and are 
shared by all instances.

Python classes are themselves objects, and the code inside the class 
body gets executed *once*, when the class is created. So in this case, 
the Date class chooses a single random month, *once*, and all instances 
share this attribute Date.month.

To get the behaviour you are after, you need to use instance attributes, 
which means referring to self. The usual place to do this is in the 
__init__ method, which is called when the instance is being 
initialised:

class Date:
    def __init__(self):
        self.month = random.randint(1,12)
        # etc.



By the way, why do you calculate a century and year separately, then add 
c+y to get the year? It would be easier to just say:

year = random.randint(1600, 3099)



-- 
Steven D'Aprano


More information about the Tutor mailing list