Search code examples
pythonclassconventions

Creating a class as a pool of another class in Python


So I have a question regarding python conventions in python classes. I want to write the most conventional way, but I am not sure if my "technique" is optimal.

In general, I have multiple instances of one class, e.g. Car(), with a method, say drive().

class Car(object):
    def drive(self):
         pass

And then I want to call car.drive() of all instances of the class Car(). The way I do this usually is:

class Cars():
    def __init__(self, num_cars):
        self.cars = [Car() for _ in range(num_cars)]

    def drive(self):
        for car in self.cars:
            car.drive()

Of course, usually Car() would have multiple methods and I would want to call all methods of all instances of Car() using the class Cars() and a method there which would call all the methods of the instances.

What do you guys think of this way of doing it? In what way could this be done better and, I guess, more Pythonic?


Solution

  • "Simple is better than complex."

    Just use a list and call it cars?