Before using enums, vehicle types are plain strings prone to typos and inconsistent values. After applying enums, only predefined VehicleType values are allowed, preventing errors and improving code clarity.
### Before: Using plain strings (error-prone)
class Vehicle:
def __init__(self, vehicle_type):
self.vehicle_type = vehicle_type # No validation
car = Vehicle('car')
motorcycle = Vehicle('motorcycle') # Typo fixed here
### After: Using enums (safe and clear)
from enum import Enum
class VehicleType(Enum):
CAR = 'car'
MOTORCYCLE = 'motorcycle'
TRUCK = 'truck'
class Vehicle:
def __init__(self, vehicle_type: VehicleType):
self.vehicle_type = vehicle_type
car = Vehicle(VehicleType.CAR)
motorcycle = Vehicle(VehicleType.MOTORCYCLE) # No typo possible
# Trying to create with invalid type raises error
# invalid_vehicle = Vehicle('motocycle') # ValueError: 'motocycle' is not a valid VehicleType