同一类别的多个对象中的随机数生成

时间:2020-02-15 20:52:12

标签: python python-3.x class random

在此示例代码中,我正在使用随机x值在列表中创建100个对象,但是问题是所有创建的对象都具有相同的x值。我尝试在网上搜索解决方案,但找不到任何方法。

import random
list = []
class object:
    x = random.randint(1,1000)

for i in range(1,101):
    list.append(object())

for i in range(1,100):
    print(list[i].x)

1 个答案:

答案 0 :(得分:1)

在Python文档中阅读Class and Instance Variables,以澄清您的具体困惑。

通常来说,实例变量用于每个实例唯一的数据,而类变量用于该类的所有实例共享的属性和方法:

class Dog:

    kind = 'canine'         # class variable shared by all instances

    def __init__(self, name):
        self.name = name    # instance variable unique to each instance

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind                  # shared by all dogs 'canine'
>>> e.kind                  # shared by all dogs 'canine'
>>> d.name                  # unique to d 'Fido'
>>> e.name                  # unique to e 'Buddy' ```

@rassar所建议的,您正在寻找的是:

class Obj:
    def __init__(self):
        self.x = random.randint(1,1000)

a = Obj()
b = Obj()
c = Obj()

print(a.x, b.x, c.x)