Python Lesson 21: Inheritance
Inheritance lets a class extend another class, inheriting all its attributes and methods. It models “is-a” relationships and avoids repeating code.
Basic Inheritance
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def breathe(self):
print(f"{self.name} is breathing")
def __str__(self):
return f"{self.name} (age {self.age})"
# Dog INHERITS from Animal
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age) # call parent __init__
self.breed = breed
def bark(self):
print(f"{self.name} says: Woof!")
dog = Dog("Rex", 3, "German Shepherd")
dog.breathe() # inherited from Animal
dog.bark() # Dog's own method
print(dog) # uses Animal's __str__
Overriding Methods
class Animal:
def speak(self):
print("Some sound...")
class Dog(Animal):
def speak(self): # override
print("Woof!")
class Cat(Animal):
def speak(self): # override
print("Meow!")
class Duck(Animal):
def speak(self): # override
print("Quack!")
animals = [Dog(), Cat(), Duck()]
for animal in animals:
animal.speak() # each calls its own version
# Woof!
# Meow!
# Quack!
Real Example: Employee System
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def get_info(self):
return f"{self.name}: ${self.salary:,}/year"
class Manager(Employee):
def __init__(self, name, salary, team_size):
super().__init__(name, salary)
self.team_size = team_size
def get_info(self):
base = super().get_info()
return f"{base} | 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):
base = super().get_info()
return f"{base} | Language: {self.language}"
boss = Manager("Alice", 120000, 8)
dev = Developer("Bob", 95000, "Python")
print(boss.get_info())
print(dev.get_info())
🏋️ Practice Task
Create a Shape hierarchy. Base class Shape has color attribute and area() method returning 0. Circle(Shape) and Rectangle(Shape) override area() with their own formulas. Create one of each and print their colors and areas.
💡 Hint: Circle area = pi * r^2. Rectangle area = width * height. Use import math and math.pi.