-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23_inheritance_tutorial.py
More file actions
309 lines (236 loc) · 6.76 KB
/
23_inheritance_tutorial.py
File metadata and controls
309 lines (236 loc) · 6.76 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# ========== INHERITANCE ==========
# 1. Basic inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
# Dog inherits Animal
class Dog(Animal):
def bark(self):
print(f"{self.name} barks: Woof-woof!")
dog = Dog("Bobik")
dog.speak() # Inherited method
dog.bark() # Own method
# 2. Method overriding
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Cat(Animal):
# Override speak method
def speak(self):
print(f"{self.name} meows: Meow!")
class Dog(Animal):
def speak(self):
print(f"{self.name} barks: Woof-woof!")
cat = Cat("Murka")
dog = Dog("Bobik")
cat.speak() # Meows
dog.speak() # Barks
# 3. Calling parent class method via super()
class Animal:
def __init__(self, name):
self.name = name
print(f"Animal created: {name}")
class Dog(Animal):
def __init__(self, name, breed):
# Call parent class constructor
super().__init__(name)
self.breed = breed
print(f"Breed: {breed}")
dog = Dog("Bobik", "Shepherd")
print(f"{dog.name} - {dog.breed}")
# 4. Extending parent method
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"My name is {self.name}, I am {self.age} years old")
class Employee(Person):
def __init__(self, name, age, job_title):
super().__init__(name, age)
self.job_title = job_title
def introduce(self):
# First call parent method
super().introduce()
# Then add our logic
print(f"I work as: {self.job_title}")
employee = Employee("Pavel", 25, "Developer")
employee.introduce()
# 5. Multiple inheritance
class Flyable:
def fly(self):
print("I can fly")
class Swimmable:
def swim(self):
print("I can swim")
class Duck(Flyable, Swimmable):
def quack(self):
print("Quack-quack!")
duck = Duck()
duck.fly()
duck.swim()
duck.quack()
# 6. Diamond problem and MRO (Method Resolution Order)
class A:
def method(self):
print("Method from A")
class B(A):
def method(self):
print("Method from B")
class C(A):
def method(self):
print("Method from C")
class D(B, C):
pass
d = D()
d.method() # Which method will be called?
# Check method resolution order (MRO)
print(f"MRO: {D.__mro__}")
# MRO: D -> B -> C -> A -> object
# 7. Type checking and inheritance
class Animal:
pass
class Dog(Animal):
pass
dog = Dog()
# isinstance - checks if object is an instance of a class
print(f"isinstance(dog, Dog): {isinstance(dog, Dog)}") # True
print(f"isinstance(dog, Animal): {isinstance(dog, Animal)}") # True (inheritance!)
print(f"isinstance(dog, object): {isinstance(dog, object)}") # True (all inherit object)
# issubclass - checks if class is a subclass of another class
print(f"issubclass(Dog, Animal): {issubclass(Dog, Animal)}") # True
print(f"issubclass(Dog, Dog): {issubclass(Dog, Dog)}") # True
print(f"issubclass(Animal, Dog): {issubclass(Animal, Dog)}") # False
# 8. Abstract base classes (ABC)
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass # Abstract method (must be implemented in subclasses)
@abstractmethod
def perimeter(self):
pass
# Cannot create instance of abstract class
# shape = Shape() # TypeError
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
rect = Rectangle(5, 3)
print(f"Area: {rect.area()}")
print(f"Perimeter: {rect.perimeter()}")
# 9. Polymorphism
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof-woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class Cow(Animal):
def speak(self):
return "Moo!"
# Function works with any Animal
def animal_sound(animal):
print(animal.speak())
animals = [Dog(), Cat(), Cow()]
for animal in animals:
animal_sound(animal)
# 10. Composition vs Inheritance
# Inheritance: "is-a"
class Vehicle:
pass
class Car(Vehicle): # Car IS-A vehicle
pass
# Composition: "has-a"
class Engine:
def start(self):
print("Engine started")
class Car:
def __init__(self):
self.engine = Engine() # Car HAS-A engine
def start(self):
self.engine.start()
# Prefer composition over inheritance!
# 11. Mixins
class LoggerMixin:
def log(self, message):
print(f"[LOG] {message}")
class TimestampMixin:
def get_timestamp(self):
from datetime import datetime
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
class User(LoggerMixin, TimestampMixin):
def __init__(self, name):
self.name = name
def login(self):
self.log(f"{self.name} logged in at {self.get_timestamp()}")
user = User("Pavel")
user.login()
# 12. Overriding __init__ with default parameters
class Animal:
def __init__(self, name, age=0):
self.name = name
self.age = age
class Dog(Animal):
def __init__(self, name, age=0, breed="Unknown"):
super().__init__(name, age)
self.breed = breed
dog1 = Dog("Bobik")
dog2 = Dog("Sharik", 5, "Shepherd")
print(f"{dog1.name}: {dog1.age} years old, {dog1.breed}")
print(f"{dog2.name}: {dog2.age} years old, {dog2.breed}")
# 13. Practical example: employee hierarchy
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def get_info(self):
return f"{self.name}: ${self.salary}"
class Manager(Employee):
def __init__(self, name, salary, team_size):
super().__init__(name, salary)
self.team_size = team_size
def get_info(self):
return f"{super().get_info()}, Team: {self.team_size} people"
class Developer(Employee):
def __init__(self, name, salary, language):
super().__init__(name, salary)
self.language = language
def get_info(self):
return f"{super().get_info()}, Language: {self.language}"
employees = [
Manager("Ivan", 5000, 10),
Developer("Pavel", 4000, "Python"),
Developer("Maria", 4500, "JavaScript")
]
for employee in employees:
print(employee.get_info())
# 14. Inheritance chain
class A:
def method(self):
print("A.method")
class B(A):
def method(self):
print("B.method")
super().method() # Call parent method
class C(B):
def method(self):
print("C.method")
super().method() # Call parent method
c = C()
c.method()
# Will output:
# C.method
# B.method
# A.method