Home > Software design >  class creates own objekts
class creates own objekts

Time:08-31

Is it possible for a class to create a number of objects n if I assign n a value? Assuming I have 100 cars that are identical and I want to create an object for each car, I could call a class that creates 100 objects (cars). I couldn't find anything about it on the internet and I don't know what exactly to look for. thanks for the replies

CodePudding user response:

You could make use of a static factory method:

class Car:
  def __init__(self, ...):
    ...
  
  @classmethod
  def make_car_array(cls, n=100):
    return [Car() for i in range(n)]

and then call

array_of_cars = Car.make_car_array()
  • Related