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?

3
  • 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 stackoverflow.com/questions/3451779/… Commented Oct 23, 2020 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. Commented Oct 23, 2020 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. Commented Oct 25, 2020 at 8:49

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.