Introduction
Inheritance allows creating new classes based on existing ones. Polymorphism lets objects of different types be treated uniformly.
Method Resolution Order
class A:
def method(self):
return "A"
class B(A):
def method(self):
return "B"
class C(A):
def method(self):
return "C"
class D(B, C):
pass
d = D()
print(d.method()) # B (MRO: D -> B -> C -> A)
super() Function
class Parent:
def __init__(self, name):
self.name = name
class Child(Parent):
def __init__(self, name, age):
super().__init__(name) # Call parent's __init__
self.age = age
Abstract Classes
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
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)
Practice Problems
- Create a shape hierarchy with area calculations
- Use super() to call parent methods
- Implement abstract base class
- Demonstrate method overriding
- Show how MRO works with multiple inheritance