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?
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:
Default parameters values
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
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