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?