因此,我从同一个类创建了x个实例,并且我希望每个实例都有一个包含10个随机数的列表。问题是,当我实例化它们时,它会给所有实例提供相同的列表。我做了一些研究,我知道我做错了什么。基本上我认为我不应该使用.append()方法,因为它扩展了原始类的List属性。这里有云来自同一类的Python实例以及它们自己的随机数列表
from random import randint
class Vehicle():
List = []
def __init__(self):
for i in range(10):
Vehicle.List.append(randint(0,10))
from Vehicle import Vehicle
class Instances():
vehicles = []
def __init__(self):
for i in range(10):
new_vehicle = Vehicle():
Instances.vehicles.append(new_vehicle)
当我实例的实例类,它会所有的罚款,但来自各车辆的情况下,列表属性都是平等的,他们都有长度= 100。现在,我得到的长度= 100,因为是10个实例x 10附加每个实例。最大的问题是,我如何从Vehicle类中获得10个实例,并且它们都具有10个具有所需长度(即10)的随机数的唯一列表?
我认为你必须使用self.List.append(RAND int(0,10))而不是Vehicle.List.append(randint(0,10))。与您的Instances类相同。 – user2746752