python 如何定义 random_定义python类时,如何在其中设置随机变量?

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.

解决方案

The reason your never getting a different gender is because the gender attribute is a class variable. Once Python creates your class object Person, the value of gender is never computed again. You need to make the gender variable an instance attribute. That means the gender will be computed on a per instance basis, instead of per class definition. eg:

import random

class Person:

def __init__(self, name):

self.name = name

alias= random.randint(1, 3)

if alias == 2:

self.gender = 'Male'

else:

self.gender = 'Female'

r= Person('rachel')

s= Person('Stanky')

print(r.gender)

print(s.gender)

Which outputs

Female

Male

On a side note, I think a much better choice for your task would be to use random.choice() to select a random gender from a list of genders(male or female):

from random import choice

class Person:

genders = ('Male', 'Female', 'Female')

def __init__(self, name):

self.name = name

self.gender = choice(Person.genders)

rachel = Person('Rachel')

stanky = Person('Stanky')

print(rachel.gender)

print(stanky.gender)

Notice in my example above, Person.genders is a class variable. This is on purpose. Because we only need to create a list of genders once, we can make the list a class level variable.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值