When defining a python class, how to set a random variable in it?

Viewed 5634

Say I have a class called Person, which will have only the person's name and gender.

The gender should be randomly selected from Male and Female. To do that, I import the random.randint() function. The random gender is determined according to the random int.

import random

class Person:
    alias = random.randint(1, 3)
    if alias == 2:
        gender = 'Male'
    else:
        gender = 'Female'

    def __init__(self, name):
        self.name = name

r = Person('rachel')
s = Person('Stanky')
print(r.gender)
print(s.gender)

However, the result I get for different person from this class all have the same gender. My understanding is the randint is fixed once been generated. My question is how to make it different for each class instance.

4 Answers
Related