Lesson 25 of 34 · Classes & OOP
Python Inheritance and super()
Classes often share a lot: a goblin and a dragon are both enemies with a name and health, but they attack differently. Inheritance lets you write the shared parts once in a base class (or parent) and create subclasses (children) that reuse, replace or extend that behaviour.
Creating a subclass
Put the parent class in parentheses after the new class name:
class Enemy:
def __init__(self, name, health):
self.name = name
self.health = health
def describe(self):
return f"{self.name} ({self.health} HP)"
def attack(self):
return 3
class Goblin(Enemy):
pass
grub = Goblin("Grub", 30)
print(grub.describe()) # Grub (30 HP)
print(grub.attack()) # 3
Goblin defines nothing of its own, yet it has everything Enemy has — including __init__.
Overriding methods
A subclass can replace a parent method by defining one with the same name. Python always looks for a method on the object's own class first, then walks up to the parent:
class Dragon(Enemy):
def attack(self):
return 40
print(Dragon("Smolder", 500).attack()) # 40
print(Goblin("Grub", 30).attack()) # 3
Extending the parent with super()
Often you don't want to replace the parent's behaviour but add to it. super() gives you access to the parent class's version of a method. The most common use is in __init__, so the parent can set up its attributes before the child adds its own:
class Archer(Enemy):
def __init__(self, name, health, arrows):
super().__init__(name, health) # sets name and health
self.arrows = arrows # the extra bit
def describe(self):
return super().describe() + f" with {self.arrows} arrows"
archer = Archer("Fen", 40, 12)
print(archer.describe()) # Fen (40 HP) with 12 arrows
Without the super().__init__(...) call, archer.name would never be set and describe() would fail with an AttributeError.
Polymorphism
Because every subclass answers to the same method names, code can work with any of them without caring which one it got:
enemies = [Goblin("Grub", 30), Dragon("Smolder", 500)]
total = sum([enemy.attack() for enemy in enemies]) # 43
Each object runs its own version of attack(). This idea — one interface, many implementations — is called polymorphism.
Checking types
isinstance() respects inheritance; issubclass() compares classes:
print(isinstance(archer, Archer)) # True
print(isinstance(archer, Enemy)) # True — an Archer *is an* Enemy
print(issubclass(Dragon, Enemy)) # True
print(type(archer) is Enemy) # False — its exact type is Archer
Every class ultimately inherits from Python's built-in object. Python also supports multiple inheritance (class C(A, B):), but keep it for special cases such as small "mixin" classes.
Inheritance or composition?
Use inheritance for a genuine "is a" relationship: an archer is an enemy. For "has a" relationships — a hero has an inventory — store the other object as an attribute instead. This is called composition, and it keeps class hierarchies shallow and flexible.
Common mistakes
- Forgetting
super().__init__(...)in a subclass's__init__, so the parent's attributes never get created. - Passing
selftosuper()methods: writesuper().describe(), notsuper().describe(self). - Overriding with an incompatible signature, which breaks code that treats all subclasses the same way.
- Deep inheritance trees: more than two or three levels usually means composition would be simpler.
Assignment
The starter code contains a finished Character base class. Add two subclasses:
Warrior(Character):__init__(self, name, health, armor)calls the parent initializer and storesarmor.attack_damage()returns12.describe()returns the parent's description followed by" [armor <armor>]", e.g."Brom (120 HP) [armor 5]". Usesuper().
Mage(Character):__init__(self, name, health, mana)calls the parent initializer and storesmana.attack_damage()casts a spell whenmanais at least10: it subtracts 10 mana and returns20. Otherwise it falls back to the parent's attack viasuper()(which returns5).describe()is inherited unchanged.
brom = Warrior("Brom", 120, 5)
brom.describe() # "Brom (120 HP) [armor 5]"
ilsa = Mage("Ilsa", 80, 15)
ilsa.attack_damage() # 20 (mana drops to 5)
ilsa.attack_damage() # 5 (not enough mana: the basic attack)Premium lesson
Unlock the full Learn Python course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Inheritance in other languages
- JavaScript Inheritance: extends, super and static · JavaScript
- Go Struct Embedding and Composition · Go
- Java Inheritance: extends and super · Java
- C# Inheritance: virtual, override and base · C#
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .