Inheritance & super()
Lesson 5 of 6 · View course roadmap
Learn the idea
Inheritance lets a class reuse and extend another: class Cat(Animal) means Cat gets everything Animal has, and can add or override.
- Child classes inherit all methods and attributes
- Override a method by redefining it with the same name
super().__init__(...)— call the parent's constructor from the child'sisinstance(obj, Animal)— True for Animal and any subclass instance
Rule of thumb: inheritance models an is-a relationship (a Cat is an Animal). If it's a has-a relationship, use composition (store the object as an attribute) instead.
Where you'll use this
Flask views, Django models, unittest.TestCase, PyTorch nn.Module — professional Python is largely subclassing framework base classes and overriding the methods they document.
Common mistakes
- Forgetting
super().__init__(...)in the child — parent attributes silently never get created, then explode later as AttributeError. - Inheriting for code reuse when there's no is-a relationship — a Car is not an Engine; it has one. Prefer composition.
- Deep inheritance towers (A→B→C→D) — two levels is usually the sane maximum.
Pro tip
isinstance(obj, Animal) is True for subclasses too — that's the point of polymorphism: code written for Animal automatically works with every Cat and Dog ever subclassed.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +35 XP
Build Shape with __init__(self, name) and a method area() returning 0. Then Square(Shape) whose __init__(self, side) calls super().__init__("square") and overrides area(). Create a Square with side 6 and print its name and area.
square 36
print(sq.name, sq.area())
class Shape:
def __init__(self, name):
self.name = name
def area(self):
return 0
class Square(Shape):
def __init__(self, side):
super().__init__("square")
self.side = side
def area(self):
return self.side ** 2
sq = Square(6)
print(sq.name, sq.area())
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.