-1

i want to create multiple objects with diferent names at once.

For example

class Car:
    def __init__(self, color):
        self.color = color

And i need to create n objects when the program first run

car_1 = Car("blue")
car_2 = Car("Red")
#...
car_n = Car("color_n")

Is there a way to do this in python3? All the things i've tried just create one object and change its name or overwhite the objects information o simply fails at running. I can't use exec() or eval()

Thanks

Extra: I need the thing before because i need to store n Client's information whenever i run the program to work with it (that info is stored in a .csv file). Do i need to do the thing i mentioned before or is there another way to deal with this kind of data management?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Birivera
  • 37
  • 8

1 Answers1

1

You can create a list of Cars objects, by list comprehension

class Car:
    def __init__(self, color):
        self.color = color
    def __repr__(self):
        return '{}({!r})'.format(self.__class__.__name__, self.color)

colors=['red', 'blue', 'green',]
cars_objects = [Car(color) for color in colors]
print(cars_objects)

return

[Car('red'), Car('blue'), Car('green')]

__repr__ function in Car Class creates a "more readable" (and parseable) representation of Car object instead of "<__main__.Car object at 0x7f5b38a2c400>"

alvarez
  • 456
  • 3
  • 9
  • 1
    Consider making the `repr` version parseable; for instance, `'{}({!r})'.format(self.__class__.__name__, self.color)`. This would show e.g. `Car('red')`. Makes it easier when replicating values for debugging and such. From `__repr__` documentation: [If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).](https://docs.python.org/3/reference/datamodel.html#object.__repr__) – Yann Vernier Aug 15 '17 at 11:03
  • @YannVernier You're absolutely right for this case. I edited my answer. Now the value returned by __repr__ could be used to recreate Car objects. – alvarez Aug 15 '17 at 11:23