64 lines
2.9 KiB
Python
64 lines
2.9 KiB
Python
class Car():
|
|
def __init__(self, make: str, model: str, year: int) -> None:
|
|
self.make = make
|
|
self.model = model
|
|
self.year = year
|
|
|
|
def __str__(self) -> str:
|
|
return f"{self.year} {self.make} {self.model}"
|
|
|
|
def __repr__(self) -> str:
|
|
return f"Car(make={self.make}, model={self.model}, year={self.year})"
|
|
|
|
def __eq__(self, value):
|
|
if not isinstance(value, Car):
|
|
return NotImplemented
|
|
return (self.make, self.model, self.year) == (value.make, value.model, value.year)
|
|
|
|
Honda: Car = Car("Honda", "Civic", 2020)
|
|
Toyota: Car = Car("Toyota", "Corolla", 2021)
|
|
|
|
# Instance creation and string representation
|
|
class ElectricCar(Car):
|
|
def __init__(self, make: str, model: str, year: int, battery_size: int) -> None:
|
|
super().__init__(make, model, year)
|
|
self.battery_size = battery_size
|
|
|
|
def __str__(self) -> str:
|
|
return f"{self.year} {self.make} {self.model} with a {self.battery_size}-kWh battery"
|
|
|
|
def __repr__(self) -> str:
|
|
return f"ElectricCar(make={self.make}, model={self.model}, year={self.year}, battery_size={self.battery_size})"
|
|
|
|
def __eq__(self, value):
|
|
if not isinstance(value, ElectricCar):
|
|
return NotImplemented
|
|
return (self.make, self.model, self.year, self.battery_size) == (value.make, value.model, value.year, value.battery_size)
|
|
|
|
# use the classes
|
|
Tesla: ElectricCar = ElectricCar("Tesla", "Model 3", 2022, 75)
|
|
myHybridCar: ElectricCar = ElectricCar("Nissan", "Leaf", 2021, 40)
|
|
print(myHybridCar == Tesla) # Output: False
|
|
print(repr(Tesla)) # Output: ElectricCar(make=Tesla, model=Model 3, year=2022, battery_size=75)
|
|
print(str(Tesla)) # Output: 2022 Tesla Model 3 with a 75-kWh battery
|
|
print(Honda == Tesla) # Output: False
|
|
print(Tesla == ElectricCar("Tesla", "Model 3", 2022, 75)) # Output: True
|
|
print(Tesla == ElectricCar("Tesla", "Model S", 2022, 100)) # Output: False
|
|
|
|
#inheritance and method overriding
|
|
class HybridCar(ElectricCar):
|
|
def __init__(self, make: str, model: str, year: int, battery_size: int, fuel_type: str) -> None:
|
|
super().__init__(make, model, year, battery_size)
|
|
self.fuel_type = fuel_type
|
|
|
|
def __str__(self) -> str:
|
|
return f"{self.year} {self.make} {self.model} with a {self.battery_size}-kWh battery runs on {self.fuel_type}"
|
|
|
|
def __repr__(self) -> str:
|
|
return f"HybridCar(make={self.make}, model={self.model}, year={self.year}, battery_size={self.battery_size}, fuel_type={self.fuel_type})"
|
|
|
|
myHybridCar: HybridCar = HybridCar("Toyota", "Prius", 2021, 1.3, "Gasoline")
|
|
print(myHybridCar) # Output: 2021 Toyota Prius with a 1.3-kWh battery runs on Gasoline
|
|
print(repr(myHybridCar)) # Output: HybridCar(make=Toyota, model=Prius, year=2021, battery_size=1.3, fuel_type=Gasoline)
|
|
print(str(myHybridCar)) # Output: 2021 Toyota Prius with a 1.3-kWh battery and runs on Gasoline
|