Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random number for class attribute

I have the following code:

from numpy import random

class Person():

    def __init__(self, name, age=random.randint(18,65)):
        self.name = name
        self.age = age

I want age to be a random number between 18 and 65, unless explicitly specified. However, when I create different instances of this class, like so:

p1 = Person('Bob')
p2 = Person('Sue')
p3 = Person('Jeff')

Each person always have the same age. How can I fix this?

like image 690
Dan Avatar asked Sep 14 '25 20:09

Dan


2 Answers

The reason for that behaviour is that default value for attributes is being initialised and set just once, so code snippet random.randint(18,65) would be executed and set as default value for age, that is the reason for having same default value for age if age not provided.

To fix problem set the default value to None and perform check and assign of random value if needed:

from numpy import random


class Person():

    def __init__(self, name, age=None):
        if age is None:
            age = random.randint(18,65)
        self.name = name
        self.age = age

Useful info regarding default attributes:

like image 73
Andriy Ivaneyko Avatar answered Sep 17 '25 09:09

Andriy Ivaneyko


The reason the age is always the same is because the value for your age parameter is defined when the method __init__ is defined and it wont be recreated every time you call your method, move the instantiation of the variable age inside the method if you want this to change every time the method is called

from numpy import random

class Person():
    def __init__(self, name, age=None):
        self.name = name
        self.age = age if age else random.randint(18, 65)

p1 = Person('Bob')
p2 = Person('Sue', 20)
p3 = Person('Jeff')

print(p1.age)
>> 56
print(p2.age)
>> 20
print(p3.age)
>> 20

print(Person('Sue', 20).age)
>> 20
like image 29
AK47 Avatar answered Sep 17 '25 10:09

AK47