-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinheritance.py
More file actions
68 lines (53 loc) · 2.16 KB
/
inheritance.py
File metadata and controls
68 lines (53 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Base class: Vehicle
class Vehicle:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
self.is_running = False
def start_engine(self):
self.is_running = True
print(f"The {self.year} {self.brand} {self.model} engine is now running.")
def stop_engine(self):
self.is_running = False
print(f"The {self.year} {self.brand} {self.model} engine has stopped.")
def get_info(self):
return f"{self.year} {self.brand} {self.model}"
# Single Inheritance: Car extends Vehicle
class Car(Vehicle):
def __init__(self, brand, model, year, num_doors, fuel_type):
super().__init__(brand, model, year)
self.num_doors = num_doors
self.fuel_type = fuel_type
self.trunk_open = False
def honk_horn(self):
print(f"The {self.brand} {self.model} is honking: Beep! Beep!")
def open_trunk(self):
self.trunk_open = True
print(f"The {self.brand} {self.model} trunk is now open.")
def get_info(self):
base = super().get_info()
return f"{base} — {self.num_doors} doors, {self.fuel_type} engine"
# Multilevel Inheritance: ElectricCar extends Car
class ElectricCar(Car):
def __init__(self, brand, model, year, num_doors, battery_capacity):
super().__init__(brand, model, year, num_doors, fuel_type="Electric")
self.battery_capacity = battery_capacity # in kWh
def charge(self):
print(f"The {self.brand} {self.model} is charging its {self.battery_capacity} kWh battery.")
if __name__ == "__main__":
# Instance of Car (single inheritance)
my_car = Car("Toyota", "Camry", 2023, 4, "Hybrid")
my_car.start_engine()
my_car.honk_horn()
my_car.open_trunk()
print("Info:", my_car.get_info())
my_car.stop_engine()
print("\n---\n")
# Instance of ElectricCar (multilevel inheritance)
tesla = ElectricCar("Tesla", "Model S", 2025, 4, battery_capacity=100)
tesla.start_engine()
tesla.charge()
tesla.honk_horn()
print("Info:", tesla.get_info())
tesla.stop_engine()