Skip to content
Inheritance and Polymorphism
step 1/7

Reading — step 1 of 7

Learn

~3 min readObject-Oriented Programming

You could copy-paste a class for different variants — but then bug fixes happen N times. Inheritance lets you build a base class with shared logic, then create specialized versions that ADD or REPLACE behavior. The specialized classes inherit everything from the base and only define what's different.

Polymorphism is the partner concept: different classes implementing the same method, so you can use them interchangeably.

Basic inheritance

python

The parenthesized name in class Dog(Animal): says "Dog IS-A kind of Animal." Dog gets all of Animal's attributes and methods automatically.

Overriding methods

Subclasses can REPLACE inherited methods:

python

When you call a method, Python checks the subclass first, then walks up to parents until it finds one.

super() — call the parent's version

python

super() gives you the parent class. Use it when you want to ADD to a parent's behavior rather than replace it. Common in __init__ so the parent's setup still runs.

Polymorphism — same interface, different behavior

python

The loop doesn't know or care whether each shape is a Rectangle or Circle — it just calls area(). That's polymorphism: different classes implementing the same interface, used interchangeably.

Duck typing — Python's twist

In Python, you don't even NEED inheritance for polymorphism — you just need the right method:

python

"If it walks like a duck and quacks like a duck, it IS a duck." Python doesn't care about declared types — it just calls the method.

isinstance() — check at runtime

python

isinstance() walks the inheritance tree. It's preferred over type(rex) is Dog (which doesn't follow inheritance).

Multiple inheritance — exists, use carefully

A class can inherit from multiple parents. Useful for mixins (reusable bits of behavior). For deep hierarchies, multiple inheritance gets complex (Method Resolution Order, diamond problem) — avoid for beginners.

Common mistakes

  • Forgetting super().__init__() in subclass __init__ — the parent's setup never runs.
  • Calling parent methods directly with class name: Animal.__init__(self, name) works but super().__init__(name) is cleaner.
  • Making everything inherit from a deep tree when composition (HAS-A) would be simpler.
  • Confusing IS-A with HAS-A: a Car HAS-A Engine, it isn't an Engine. Use composition (engine attribute), not inheritance.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…