0

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?

Sean Pianka
  • 2,157
  • 2
  • 27
  • 43
  • 1
    This is known as composition/accumulation. The `Cars` class accumulates `Car` objects. In Principle, there's nothing wrong with this. Maybe `Cars` should have a better name such das `CarPool`, and maybe not using a class for the second code block at all (just the list of `Car` instances) is the better solution if you don't want to give the `Cars` class more meaningful methods. – timgeb Oct 16 '18 at 16:30
  • Had to find more out what Pythonic meant. [SO Pythonic](https://stackoverflow.com/questions/25011078/what-does-pythonic-mean). Looks Pythonic to me. One note is that not everyone follows the precise written convention; making sure your consistent in your code writing is also important idea too. Focusing to much on being perfect may detract from learning what is really important. – Mr00Anderson Oct 16 '18 at 16:55

1 Answers1

2

"Simple is better than complex."

Just use a list and call it cars?

Vikrant Sharma
  • 419
  • 3
  • 6
  • Would you do that even if there were multiple methods of `Car()` that you wanted to call for all instances? E.g. `steer()`, `break()`, `blink()` and so on. – Mathias Stensrud Oct 16 '18 at 16:57
  • 2
    Yes, the equivalent methods in a `Cars` object would be wrappers and an extra level of indirection anyway. But if a bunch of cars together have some meaning in your application, then as timgeb mentions in the comments, something like `CarPool` might make more sense. – Vikrant Sharma Oct 16 '18 at 17:08