Arthur Vinicius
Arthur Vinicius

Reputation: 47

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

So I create a x 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 (i.e. 10) ?

Upvotes: 0

Views: 219

Answers (2)

Tim Peters
Tim Peters

Reputation: 70602

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))

Upvotes: 2

tacaswell
tacaswell

Reputation: 87386

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))

Upvotes: 4

Related Questions