Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Object-Oriented Python

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Python

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
Method lookup for dog.speak(): the dog object, no; class Dog, no; class Animal, yes, so Python stops there dog (object) speak? no class Dog speak? no class Animal speak? yes, stop Python walks from child to parent and stops at the first match.
The lookup for dog.speak(). Dog.__bases__ is the link Python walks along.

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

IdeaWhat to remember
class Dog(Animal)the child gets everything from the parent
Method lookupobject, class, parent; stops at the first match
Child __init__replaces the parent's; call super().__init__(...)
Overridingreplace it, or extend it with super().method()
isinstance vs typeisinstance follows the family, type is the exact class
Polymorphismone call, each object runs its own version
Duck typingPython 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 20 of 48

Previous
Python Classes and Objects: __init__, self and PEP 8 Names
Next post
Python Multiple Inheritance, the MRO and Mixins

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.

On this page

  • Your first child class
  • How Python finds a method
  • When a child writes its own __init__
  • The super() function
  • Method overriding: replace or extend
  • isinstance and issubclass
  • Polymorphism: many forms
  • Duck typing
  • A family of shapes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.