Lesson 3: Inheritance & Polymorphism
What You'll Learn
- Create child classes that inherit from a parent class
- Override methods and call the parent using
super() - Understand polymorphism — one interface, many behaviors
- Use
isinstance()andissubclass()
Inheritance
Inheritance lets a new class (child/subclass) automatically get all the attributes and methods of an existing class (parent/superclass). You extend it by adding new methods or overriding existing ones.
Inheritance models "is-a" relationships: a Dog is-an Animal. A SavingsAccount is-a BankAccount.
super()
When a child class overrides __init__, it should usually call super().__init__(...) to run the parent's setup code first. super() returns a proxy to the parent class and works correctly even in complex multiple-inheritance hierarchies.
super().__init__(name, age) — runs the parent constructor so parent attributes are set before adding child-specific ones.Polymorphism
Polymorphism means "many forms." In Python, different classes can define the same method name, and calling that method on any of them produces the correct behavior for that object's type. This lets you write code that works with any compatible object without checking its type manually.
Quick Check
1. What does super().__init__() do in a child class?
2. Which relationship does inheritance model?
3. Polymorphism allows you to call animal.speak() on a Dog, Cat, or Bird without knowing which type. What makes this work?
4. What does isinstance(dog, Animal) return if Dog inherits from Animal?