Python · Course navigation

Python inheritance and polymorphism

Call overridden behavior through a common interface.

On this page
Before you start

Classes and methods.

  • Call overridden behavior through a common interface.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

A subclass can inherit behavior and replace a method with its own implementation. Calling the method uses the actual object's implementation.

Polymorphism means the same operation can work with different compatible objects. Python also supports this without inheritance through duck typing: the object needs the required behavior.

Code example

Python
class Animal:
    def speak(self):
        return "sound"

class Dog(Animal):
    def speak(self):
        return "woof"

class Cat(Animal):
    def speak(self):
        return "meow"

for animal in [Dog(), Cat()]:
    print(animal.speak())
Output
woof
meow

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1class Animal:
2 def speak(self):
3 return "sound"
4
5class Dog(Animal):
6 def speak(self):
7 return "woof"
8
9class Cat(Animal):
10 def speak(self):
11 return "meow"
12
13for animal in [Dog(), Cat()]:
14 print(animal.speak())

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Construct two subclass instances and visit Dog first.animal = Dog instance
—
Dispatch speak to Dog.speak.return = woof
—
Print the first returned sound.return = woof
woof
Visit the Cat instance next.animal = Cat instance
woof
Dispatch to Cat.speak.return = meow
woof
Print the second sound.return = meow
woof
meow

Behind the scenes

How Python processes this code

Python runs this source through its interpreter. It creates objects for values and resolves names as each statement runs.

Cost and common mistakes

O(n) method calls for n animals; O(n) space for the sample list.

  • Use inheritance for a meaningful substitutable relationship, not merely to reuse a few lines.
  • Changing a method's expected arguments can break callers that rely on a common interface.

Try it yourself

Add Bird with a speak method returning chirp.

Reveal answer and reasoning

Include Bird() in the list. The third line becomes chirp; the loop does not need to change.

Further reading