0

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!

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
slivinn
  • 85
  • 7
  • Relevant: https://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute – cs95 Oct 29 '17 at 23:01

1 Answers1

1

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))
yang5
  • 1,125
  • 11
  • 16
  • Thank you! I hate when working with classes to initialize variables inside the methods, but it did solved my problem! – slivinn Oct 30 '17 at 01:06