简体   繁体   中英

Python instances from the same class with their own list of random numbers

So I create ax numbers of instances from the same class, and each instance I want to have a list with 10 random numbers. The problem is when I instantiate them it's gives to all instances the same list. I did some research and I know sort of what I'm doing wrong. Basically I think I should not be using the .append() method because it's extends the List attribute from the raw class. Here it goes

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)

When I instantiate the Instances class, it goes all fine, but the List attribute from each Vehicle instances are all equal and they all have length = 100. Now I got the length = 100 because is 10 instances x 10 appends each instance. The big question is, how can i have 10 instances from Vehicle class and they all have a unique list of 10 random numbers with the desired length (ie 10) ?

You are confusing class and instances level attributes. As you code is written List is an attribute of Vehicle , that is there is one object which is List and it is shared by all of the instances of Vehicle

Try this instead:

class Vehicle():
    def __init__(self):
        self.List = []
        for i in range(10):
            self.List.append(randint(0,10))

Make List an instance variable instead of a class variable:

def __init__(self):
    self.List = []
    for i in range(10):
        self.List.append(randint(0,10))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM