Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
A child class gets everything from its parent, Python walks up and stops at the first match, and super() reaches the parent. Then polymorphism: one call, a different method for each object, with Animal, Employee and Shape examples and their real output.
What you will learn
- Build a child class and explain how Python walks up to find a method
- Call the parent's __init__ with super() and know why a child __init__ replaces it
- Override a method to replace it or extend it with super()
- Write one function that works on many classes through polymorphism and duck typing
Before you start
- Python classes, objects, __init__ and self
- Instance methods
Until now, every class you wrote stood on its own. With inheritance, one class builds on another, and you stop writing the same code twice. With polymorphism, one line of code runs a different method for each object. Both ideas are smaller than they sound.
Start in the kitchen. You have a recipe for a basic cake: flour, sugar, eggs. Now you want a chocolate cake. You don't write everything again. You say "same as the basic cake" and add the one new thing, cocoa. The parent holds what's shared, and the child gets it and adds its own. You'll also hear the parent called a base class and the child a subclass.
The test is the words "is a". A chocolate cake is a cake. A dog is an animal, a manager is an employee. But a car isn't an engine; a car has an engine, so that's not inheritance. If "is a" sounds wrong, don't inherit.
Your first child class
class Animal:
def __init__(self, name, sound):
self.name = name
self.sound = sound
def speak(self):
return f"{self.name} says {self.sound}!"
class Dog(Animal):
def fetch(self, item):
return f"{self.name} fetches the {item}"
dog = Dog("Rex", "Woof")
print(dog.speak())
print(dog.fetch("ball"))
Rex says Woof!
Rex fetches the ball
class Dog(Animal): those brackets are all it takes. Dog has one method of its own, fetch, and no __init__ at all. So when you write Dog("Rex", "Woof"), Python doesn't find __init__ on Dog and uses the one from Animal. speak isn't in Dog either, but it works. And fetch can read self.name because the name is on the same object.
How Python finds a method
There are three stops, in order: the object, its class, then the parent. vars() shows what is stored on each one, so you can check:
class Animal:
def speak(self):
return "some sound"
class Dog(Animal):
def fetch(self):
return "ball"
dog = Dog()
print("speak" in vars(dog))
print("speak" in vars(Dog))
print("speak" in vars(Animal))
print(Dog.__bases__)
print(dog.speak())
False
False
True
(<class '__main__.Animal'>,)
some sound
speak is not on the object and not in Dog. It's only in Animal. Dog.__bases__ shows the parent inside a one-item tuple. So Python walks up from child to parent and stops at the first match. Keep that word "first" in mind; the rest depends on it.
When a child writes its own __init__
A Manager is an Employee with one extra field, a department. So Manager writes its own __init__:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
class Manager(Employee):
def __init__(self, name, salary, department):
self.department = department
mgr = Manager("Alice", 95000, "Engineering")
print(mgr.department)
print(mgr.name)
Engineering
Traceback (most recent call last):
File "S03L03_Inheritance\missing_super.py", line 15, in <module>
print(mgr.name)
^^^^^^^^
AttributeError: 'Manager' object has no attribute 'name'
Python walks up and stops at the first __init__ it finds, the one in Manager. So only department gets set, and Employee's __init__ never runs. Here's the rule: a child's __init__ replaces the parent's. It doesn't add to it.
The super() function
The fix is one line:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
class Manager(Employee):
def __init__(self, name, salary, department):
super().__init__(name, salary)
self.department = department
mgr = Manager("Alice", 95000, "Engineering")
print(mgr.name)
print(mgr.salary)
print(mgr.department)
Alice
95000
Engineering
super() reaches the parent from inside the child. You don't write the parent's name and you don't pass self; Python handles both. "Alice" and 95000 go up to Employee's __init__, which fills in name and salary on this same object. Then the next line sets department. Let the parent fill in its part, then add yours. Those two lines stay in one place, so you never copy them into every child.
Method overriding: replace or extend
Overriding means a child writes a method with the same name as its parent.
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof"
class Puppy(Dog):
def speak(self):
return super().speak() + " (squeaky)"
print(Animal().speak())
print(Dog().speak())
print(Puppy().speak())
Some sound
Woof
Woof (squeaky)
For a Dog, Python stops at Dog's speak and never reaches Animal. That's replacing, and Animal itself hasn't changed. Puppy wants to add instead, so it calls super().speak(), which goes up one step to Dog, gets "Woof" and puts " (squeaky)" on the end. Two choices: replace it, or extend it with super(). Either way the closest version wins.
isinstance and issubclass
class Animal:
pass
class Dog(Animal):
pass
dog = Dog()
print(isinstance(dog, Dog))
print(isinstance(dog, Animal))
print(type(dog) == Animal)
print(type(dog) == Dog)
print(issubclass(Dog, Animal))
print(issubclass(Animal, Dog))
True
True
False
True
True
False
isinstance(dog, Animal) is True because a dog is an animal; isinstance follows the family. type() is strict and only gives the exact class, so type(dog) == Animal is False. issubclass works on classes and only goes one way, from child up to parent. In most code, reach for isinstance, because it accepts the children too.
Polymorphism: many forms
Poly means many and morph means form. Think of a power button. Press it on a fan and the blades spin. On a lamp, the light comes on. On a radio, the music starts. One action, three results, and you don't need to know what's inside. In code, the button is a method name and each object brings its own version.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
class Fish(Animal):
pass
pets = [Dog("Rex"), Cat("Tom"), Fish("Nemo")]
for pet in pets:
print(pet.name, "says", pet.speak())
Rex says Woof
Tom says Meow
Nemo says ...
The same line, pet.speak(), goes to Dog's method for Rex and Cat's for Tom. Fish has no speak, so for Nemo Python walks up to Animal and gets the three dots. The loop never checks what kind of pet it has. There's no if and no type check. Each object answers for itself.
Duck typing
Python goes one step further. These classes share no parent at all:
class Dog:
def speak(self):
return "Woof"
class Robot:
def speak(self):
return "Beep"
class Rock:
pass
def make_noise(thing):
print(thing.speak())
make_noise(Dog())
make_noise(Robot())
make_noise(Rock())
Woof
Beep
Traceback (most recent call last):
File "S03L03_Inheritance\duck_typing.py", line 21, in <module>
make_noise(Rock())
~~~~~~~~~~^^^^^^^^
File "S03L03_Inheritance\duck_typing.py", line 16, in make_noise
print(thing.speak())
^^^^^^^^^^^
AttributeError: 'Rock' object has no attribute 'speak'
If it walks like a duck and quacks like a duck, it's a duck. make_noise cares what an object can do, not which family it's from. Rock has no speak, so that call fails. Notice the first two lines still printed: Python only checks when that line runs, so that's the moment a missing method shows up.
A family of shapes
Here's everything in one small family: inheritance, super(), overriding and polymorphism.
import math
class Shape:
def __init__(self, name, color):
self.name = name
self.color = color
def area(self):
return 0
def perimeter(self):
return 0
class Circle(Shape):
def __init__(self, radius, color):
super().__init__("Circle", color)
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
class Rectangle(Shape):
def __init__(self, width, height, color):
super().__init__("Rectangle", color)
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
def print_shape_info(shape):
print(f"{shape.name} ({shape.color})")
print(f" Area: {shape.area():.2f}")
print(f" Perimeter: {shape.perimeter():.2f}")
shapes = [
Circle(5, "red"),
Rectangle(4, 7, "blue"),
]
for s in shapes:
print_shape_info(s)
Circle (red)
Area: 78.54
Perimeter: 31.42
Rectangle (blue)
Area: 28.00
Perimeter: 22.00
Shape holds what every shape has, a name and a color. Its area and perimeter return 0 because a plain shape has no formula; there's a stricter way to write that with abstract classes. Circle and Rectangle send their name and color up with super(), keep their own measurements, and override both formulas.
print_shape_info has no idea which shape it has. For the circle, pi times five squared gives 78.54. For the rectangle, four times seven is 28. One function, two shapes, nothing to change inside it. If you see a long chain of if/else on an object's type, in your code or from an AI tool, ask whether this would be simpler.
Quick recap
| Idea | What to remember |
|---|---|
class Dog(Animal) | the child gets everything from the parent |
| Method lookup | object, class, parent; stops at the first match |
Child __init__ | replaces the parent's; call super().__init__(...) |
| Overriding | replace it, or extend it with super().method() |
isinstance vs type | isinstance follows the family, type is the exact class |
| Polymorphism | one call, each object runs its own version |
| Duck typing | Python checks what an object can do, when the line runs |
Try it yourself
Add a Square class to the shapes file without touching print_shape_info. Or prompt an AI tool to write it, then read every line it gives you.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Class Methods, Static Methods and Properties: What Each One Receives
Instance methods get self, class methods get cls, static methods get nothing. Then properties, setters and deleters, with small runnable files and their real output.
Python Classes and Objects: __init__, self and PEP 8 Names
A class is the blueprint and an object is what you build from it. Car, Student, Dog, Circle and BankAccount show what __init__ and self really do, how attribute lookup works, the missing self error, and PEP 8 names.
Python Multiple Inheritance, the MRO and Mixins
A class can have two parents or a whole chain of them, and one list puts them in order: the MRO. Read it, watch Python walk it, see super() follow it, and build JsonMixin and LogMixin for a User class.
Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
Python has no private keyword: one underscore is a sign, two underscores is a rename, and nothing is locked. Then the dunder methods that let print, ==, +, len, [] and for work on your own Book, Song, Vector and Playlist objects.
