0

I have a text file with a list of car types, for example:

  • Ferrari
  • Volvo
  • Audi
  • Tesla

In my code I have the following structure

class Car(ABC):
   ...
   @abstractmethod
   def refuel(self):
       pass

class Ferrari(Car):
   ...
   def refuel(self):
       print('Refueling a Ferrari')

class Tesla(Car):
   ...
   def refuel(self):
       print('Refueling a Tesla') 

...

I want to parse the text file into a list of some sort of Car object, so that I can for example loop through it and use the refuel method.

Currently I do it this way

ferrari = Ferrari()
tesla = Tesla()
volvo = Volvo()
audi = Audi()

cars = []

with open('cars.txt', 'r') as f:
   for line in f:
       if line == 'Ferrari':
           cars.append(ferrari)
       elif line == 'Volvo':
           cars.append(volvo)
       elif line == 'Tesla':
           cars.append(tesla)
       else:
           cars.append(audi)

I'm not interested (currently) about having an instance for each text file car. I only want a way to use the method from the correct class...

Is there a more straightforward way of doing this?

RedSmolf
  • 355
  • 3
  • 11
  • What is not straightforward about the current approach? Anything else would probably be less straightforward and more bug prone. If you mean more straightforward as in less lines, then maybe look at https://stackoverflow.com/questions/3451779/how-to-dynamically-create-an-instance-of-a-class-in-python – ZombieTfk Oct 23 '20 at 12:28
  • @ZombieTfk I meant a more correct or pythonic way. They way I'm doing it works, but for every new car I would have to create a new elif-statement and create a "template" object of that class. – RedSmolf Oct 23 '20 at 12:53
  • Do you want a separate class for each car type? I'm asking, because if the name is the only difference, you could use a generic Car class and just set a name attribute. – Wups Oct 25 '20 at 08:49

0 Answers0