12
Day 12: Inheritance and Polymorphism
Chapter 12 • Intermediate
50 min
Inheritance allows you to create new classes based on existing ones. It's like creating a specialized version of an existing class.
Inheritance
Inheritance is when a new class (child) inherits properties and methods from an existing class (parent). It's like a family tree where children inherit traits from parents.
Polymorphism
Polymorphism means "many forms." It allows objects of different classes to be treated as objects of a common parent class.
Inheritance Concepts
- Parent Class (Base Class) - The class being inherited from
- Child Class (Derived Class) - The class that inherits
- Method Overriding - Child class provides its own version of a method
- Super() - Access parent class methods
- Multiple Inheritance - A class can inherit from multiple parents
Benefits:
- Code Reusability - Don't repeat code
- Hierarchical Organization - Logical class relationships
- Extensibility - Easy to add new features
- Polymorphism - Same interface, different implementations
Hands-on Examples
Inheritance Example
# Parent class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
def eat(self):
return f"{self.name} is eating"
# Child class inheriting from Animal
class Dog(Animal):
def speak(self): # Override parent method
return f"{self.name} says Woof!"
def fetch(self):
return f"{self.name} is fetching the ball"
# Another child class
class Cat(Animal):
def speak(self): # Override parent method
return f"{self.name} says Meow!"
def climb(self):
return f"{self.name} is climbing the tree"
# Create objects
dog = Dog("Buddy")
cat = Cat("Whiskers")
# Use inherited and overridden methods
print(dog.speak())
print(cat.speak())
print(dog.eat()) # Inherited method
print(cat.climb())This shows inheritance where Dog and Cat inherit from Animal. They override the speak() method but inherit the eat() method.