š
Inheritance and Polymorphism
Intermediate
100 XP
45 min
Lesson Content
Inheritance: Building on Existing Classes
Inheritance allows you to create new classes based on existing ones, reusing code and creating hierarchical relationships.
Basic Inheritance
# Parent class (base class)
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
# Child class (derived class)
class Dog(Animal):
def speak(self): # Override parent method
return f"{self.name} barks"
class Cat(Animal):
def speak(self):
return f"{self.name} meows"
# Create objects
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # Buddy barks
print(cat.speak()) # Whiskers meowsUsing super()
Call parent class methods:
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call parent __init__
self.breed = breed
# Multiple inheritance
class A:
def method(self):
return "A"
class B:
def method(self):
return "B"
class C(A, B): # Inherits from both
pass
c = C()
print(c.method()) # "A" (first in order)Method Overriding
Child classes can override parent methods:
class Shape:
def area(self):
return 0
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self): # Override parent method
return self.width * self.heightPolymorphism
Different classes can have methods with the same name:
class Circle:
def area(self):
return 3.14 * self.radius ** 2
class Rectangle:
def area(self):
return self.width * self.height
# Both have area() method
shapes = [Circle(), Rectangle()]
for shape in shapes:
print(shape.area()) # Polymorphism in action!Benefits of Inheritance
- ā Code Reuse: Don't repeat code
- ā Organization: Logical class hierarchy
- ā Maintainability: Update parent affects all children
- ā Polymorphism: Same interface, different behavior
Example Code
Create a Vehicle base class and Car/Motorcycle child classes.
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def info(self):
return f"{self.brand} {self.model}"
class Car(Vehicle):
def __init__(self, brand, model, doors):
super().__init__(brand, model)
self.doors = doors
def info(self):
return f"{super().info()} with {self.doors} doors"
class Motorcycle(Vehicle):
def info(self):
return f"{super().info()} (Motorcycle)"
# Test
car = Car("Toyota", "Camry", 4)
bike = Motorcycle("Honda", "CBR")
print(car.info())
print(bike.info())Expected Output:
Toyota Camry with 4 doors Honda CBR (Motorcycle)
Study Tips
- ā¢Read the theory content thoroughly before practicing
- ā¢Review the example code to understand key concepts
- ā¢Proceed to the Practice tab when you're ready to code