slivinn
slivinn

Reputation: 85

Is it possible to automatically create instances inside a for loop?

Q: Is it possible to automatically create instances inside a for loop:

Main.py:

from Car import Car

car_list = [
    ['red', 555, 123.04],
    ['black', 666, 203.04],
    ['green', 111, 23.04],
    ]

cars = Car()


new_car_list = []

for line in car_list:
    new_car_list.append(cars.foo(line))

Car.py

class Car:
    def __init__(self):
        self.number = int()
        self.color = str()
        self.price = float()

    def foo(self, line):
        for attribute in line:
            if isinstance(attribute,int):
                self.number = attribute
            elif isinstance(attribute, str):
                self.color = attribute
            elif isinstance(attribute, float):
                self.price = attribute
        return self

Output:

for car in new_car_list:
    print(car.number)

111

111

111

As you can see, I have a Car Class that has some attributes. In my Main file I have a List of card. My goal is to: 1) be able to create an instance for each car, and append it to a new list that contains dict,when hey key is an id number generated by the program, and the value is the instance of the car. At the end I want to be able to access the instance attributes by using the key of the dict.

Is it possible?

Thanks!

Upvotes: 0

Views: 54

Answers (1)

yang5
yang5

Reputation: 1235

The same Car object cars is being updated and appended every time in the for loop. You could do:

new_car_list = []

for line in car_list:
    car = Car()
    new_car_list.append(car.foo(line))

Upvotes: 1

Related Questions