SyntaxPilot
Courses/Python/Lesson 22

Python · Lesson 22 of 40 · 13 min

OOP 2: inheritance and polymorphism

queued

These are the notes for Python episode 22, part two of object oriented programming (OOP). In episode 21 we built a Customer class for Raju's chai shop. Now the shop needs VIP customers: exactly like a customer, plus a discount. Copy-pasting the class looks quick, but the copies drift apart and VIPs silently pay the wrong amount. So we invent inheritance (a child class that reuses its parent), overriding, super(), the method resolution order, and polymorphism: one line of code that works for many kinds of objects, including Python's duck typing. Every example below runs as-is in the SyntaxPilot compiler, with its real output from Python 3.13.

The problem: a copy-pasted class

A VIP is a customer with 10% off. The quick way is to copy Customer, rename it, and add a discount. A month later Raju adds a Rs 5 packing charge to every bill. He edits Customer... and forgets the copy.

class Customer:
    def __init__(self, name):
        self.name = name

    def bill(self, amount):
        return amount + 5      # new: packing charge

class VIPCustomer:             # copy-pasted
    def __init__(self, name, discount):
        self.name = name
        self.discount = discount

    def bill(self, amount):
        return amount - amount * self.discount // 100

print("Ravi pays", Customer("Ravi").bill(200))
print("Asha pays", VIPCustomer("Asha", 10).bill(200))

Output:

Ravi pays 205
Asha pays 180

No error, no warning: Asha gets 10% off but no packing charge. Wrong money, every single day.

Why it fails: the same rules now live in two places. Every change must be made twice, and the day you forget one copy, the copies drift apart. With ten kinds of customers it becomes hopeless.

What we want: write the customer rules once, and say "a VIP is a customer, plus a discount". That is inheritance.

Inheritance: masala chai is still chai

At the chai stall In Python
The basic chai recipe (boil, milk, sugar) the parent class class Customer: holds the shared rules
Masala chai = the same recipe + masala the child class class VIPCustomer(Customer): gets everything from the parent
Iced tea changes one step (cool it instead of serving hot) overriding: the child replaces one method with its own
"First do the basic steps, then add the masala" super() runs the parent's version

When the basic recipe changes, every version gets the change automatically. That's the whole point.

Words you need:

  • Parent class (also base class or superclass): the class being inherited from.
  • Child class (also derived class or subclass): the new class that inherits.
  • Inherit: the child automatically gets every attribute and method of the parent.

Your first child class

Put the parent's name in brackets after the child's name:

class Customer:
    def __init__(self, name):
        self.name = name

    def bill(self, amount):
        return amount + 5      # packing charge

class VIPCustomer(Customer):
    pass

asha = VIPCustomer("Asha")
print(asha.name, asha.bill(200))

Output:

Asha 205

VIPCustomer has no __init__ and no bill of its own, yet both worked: they came from Customer. When you call asha.bill(200), Python looks in VIPCustomer first, doesn't find bill, then looks in the parent Customer, and finds it.

Overriding a method

A VIP needs a discount, so the child defines its own __init__ (to store the discount) and its own bill. A method in the child with the same name as one in the parent replaces it for child objects. That's called overriding.

But watch what happens if we just write new methods:

class Customer:
    def __init__(self, name):
        self.name = name

    def bill(self, amount):
        return amount + 5      # packing charge

class VIPCustomer(Customer):
    def __init__(self, name, discount):
        self.discount = discount

    def bill(self, amount):
        return amount - amount * self.discount // 100

asha = VIPCustomer("Asha", 10)
print(asha.bill(200))
print(asha.name)

Output:

180
Traceback (most recent call last):
  File "/tmp/tmp_0077883/main.py", line 17, in <module>
    print(asha.name)
          ^^^^^^^^^
AttributeError: 'VIPCustomer' object has no attribute 'name'

Two problems:

  1. The child's __init__ replaced the parent's completely. The parent's __init__, the one that sets self.name, never ran, so the object has no name.
  2. The child's bill replaced the parent's too, so the packing charge is gone again (180, not 185).

Overriding replaces. To extend the parent instead, we need super().

super(): do the parent's part too

super() means "the parent class". super().__init__(name) runs the parent's setup; super().bill(amount) runs the parent's bill.

class Customer:
    def __init__(self, name):
        self.name = name

    def bill(self, amount):
        return amount + 5      # packing charge

class VIPCustomer(Customer):
    def __init__(self, name, discount):
        super().__init__(name)
        self.discount = discount

    def bill(self, amount):
        amount = amount - amount * self.discount // 100
        return super().bill(amount)

asha = VIPCustomer("Asha", 10)
print(asha.name, asha.bill(200))
print(Customer("Ravi").bill(200))

Output:

Asha 185
205

Asha pays 200 − 20 + 5 = 185. The packing rule is written once, in Customer. Change it to Rs 10 tomorrow and VIPs get the change automatically.

Pass on what the parent needs

super().__init__() with empty brackets is a very common mistake. The parent's __init__ still needs its arguments:

class Customer:
    def __init__(self, name):
        self.name = name

class VIPCustomer(Customer):
    def __init__(self, name, discount):
        super().__init__()
        self.discount = discount

VIPCustomer("Asha", 10)

Output:

Traceback (most recent call last):
  File "/tmp/tmpe9mlo6h6/main.py", line 10, in <module>
    VIPCustomer("Asha", 10)
    ~~~~~~~~~~~^^^^^^^^^^^^
  File "/tmp/tmpe9mlo6h6/main.py", line 7, in __init__
    super().__init__()
    ~~~~~~~~~~~~~~~~^^
TypeError: Customer.__init__() missing 1 required positional argument: 'name'

Fix: super().__init__(name).

How Python finds a method: the MRO

Picture boxes inside boxes: Customer inside VIPCustomer, and around everything a class called object, the top parent of every class in Python (even class Customer: secretly inherits from object).

When you call asha.bill(200), Python searches VIPCustomer → Customer → object and runs the first bill it finds. This search order is called the MRO, the method resolution order. Every class has it in __mro__.

Because a VIP was built from Customer, a VIP is a customer. isinstance() checks the whole family:

class Customer:
    def __init__(self, name):
        self.name = name

    def bill(self, amount):
        return amount + 5      # packing charge

class VIPCustomer(Customer):
    def __init__(self, name, discount):
        super().__init__(name)
        self.discount = discount

    def bill(self, amount):
        amount = amount - amount * self.discount // 100
        return super().bill(amount)

asha = VIPCustomer("Asha", 10)
ravi = Customer("Ravi")
print(isinstance(asha, Customer))
print(isinstance(ravi, VIPCustomer))
print(VIPCustomer.__mro__)

Output:

True
False
(<class '__main__.VIPCustomer'>, <class '__main__.Customer'>, <class 'object'>)
  • Every VIP is a customer: True.
  • A normal customer is not a VIP: False.
  • The MRO is exactly the order Python searches.

issubclass(VIPCustomer, Customer) asks the same question about classes and is True.

Polymorphism: one call, many behaviours

The shop now has a third kind of customer: staff, who pay half. To bill everyone, the obvious way is to ask each object what it is:

for c in khata:
    if type(c) == Customer:
        total = 200 + 5
    elif type(c) == VIPCustomer:
        total = 180 + 5
    elif type(c) == Staff:
        total = 100
    # a new kind? edit this again

Every new kind of customer means opening this loop and adding another branch: the copy-paste problem in a new shape. And the billing rules are now duplicated outside the classes.

The better way: don't ask "what are you?", just say c.bill(200). Each object already knows how to bill itself.

At the counter In Python
The cashier just says "please pay" the loop just calls c.bill(200)
Cash: count notes, give change Customer.bill(): amount + 5
UPI: scan the QR, enter the PIN VIPCustomer.bill(): 10% off, + 5
Card: tap or swipe Staff.bill(): half price

Poly means many, morph means form. Polymorphism = one method call, many behaviours.

class Customer:
    def __init__(self, name):
        self.name = name

    def bill(self, amount):
        return amount + 5      # packing charge

class VIPCustomer(Customer):
    def __init__(self, name, discount):
        super().__init__(name)
        self.discount = discount

    def bill(self, amount):
        amount = amount - amount * self.discount // 100
        return super().bill(amount)

class Staff(Customer):
    def bill(self, amount):
        return amount // 2

khata = [Customer("Ravi"), VIPCustomer("Asha", 10), Staff("Raju")]
for c in khata:
    print(c.name, "pays", c.bill(200))

Output:

Ravi pays 205
Asha pays 185
Raju pays 100

The same line c.bill(200) ran three different methods. Python picks the right one for each object at run time, using the MRO. Staff didn't even need its own __init__: it inherited Customer's. Add a fourth kind next year and the loop doesn't change.

Duck typing

"If it walks like a duck and quacks like a duck, it's a duck." When the loop calls c.bill(200), Python does not check that c is a Customer. It only checks: does this object have a bill method? This is duck typing.

You've used it since episode 5: len("chai"), len([1, 2]), len({}) are totally different types, one function.

class Customer:
    def __init__(self, name):
        self.name = name

    def bill(self, amount):
        return amount + 5      # packing charge

class Company:              # not a Customer at all
    def __init__(self, name):
        self.name = name

    def bill(self, amount):
        return amount + amount * 18 // 100

class Supplier:
    def __init__(self, name):
        self.name = name

for c in [Customer("Ravi"), Company("Hotel Sagar"), Supplier("Milkman")]:
    print(c.name, "pays", c.bill(200))

Output:

Ravi pays 205
Hotel Sagar pays 236
Traceback (most recent call last):
  File "/tmp/tmp42t0siye/main.py", line 20, in <module>
    print(c.name, "pays", c.bill(200))
                          ^^^^^^
AttributeError: 'Supplier' object has no attribute 'bill'
  • Company is not a child of Customer, but it has a bill method (with 18% GST), so the loop is happy.
  • Supplier has no bill, and you only find out when the call happens: AttributeError.

So inheritance is one way to share behaviour; duck typing means any object with the right methods fits. Either way the loop never asks what you are.

Common mistakes

Mistake What you see Why Fix
copy-pasting a class no error: the copies drift apart (205 vs 180) the same rules in two places class VIPCustomer(Customer):
a child __init__ without super().__init__(...) AttributeError: 'VIPCustomer' object has no attribute 'name' the parent's __init__ never ran super().__init__(name)
super().__init__() with no arguments TypeError: Customer.__init__() missing 1 required positional argument: 'name' the parent still needs its arguments super().__init__(name)
overriding bill and forgetting the parent's rule no error: the packing charge disappears overriding replaces return super().bill(amount)
calling a method an object doesn't have AttributeError: 'Supplier' object has no attribute 'bill' duck typing: no such method give the class that method
if type(c) == ...: elif ...: chains no error: grows with every new kind the loop knows too much c.bill(amount)
class VIP(Customr): (typo in the parent) NameError: name 'Customr' is not defined the parent must exist first spell it right, define the parent above
a base method that should never run wrong silent result the child forgot to override raise NotImplementedError(...) in the base

Mini project: Cash, UPI and Card payments

A base class Payment holds the amount. Cash, UPI and Card are children, each with its own pay(). The base pay() raises NotImplementedError (episode 18), which means "every child must write its own". UPI adds an ID using super().__init__.

class Payment:
    def __init__(self, amount):
        self.amount = amount
    def pay(self):
        raise NotImplementedError("each payment type must define pay()")

class Cash(Payment):
    def pay(self):
        return f"Cash: Rs {self.amount}"

class UPI(Payment):
    def __init__(self, amount, upi_id):
        super().__init__(amount)
        self.upi_id = upi_id
    def pay(self):
        return f"UPI: Rs {self.amount} from {self.upi_id}"

class Card(Payment):
    def pay(self):
        fee = self.amount * 2 // 100
        return f"Card: Rs {self.amount + fee} (Rs {fee} fee)"

for p in [Cash(120), UPI(250, "asha@okbank"), Card(500)]:
    print(p.pay())

Output:

Cash: Rs 120
UPI: Rs 250 from asha@okbank
Card: Rs 510 (Rs 10 fee)

One loop, three behaviours. And if someone adds a payment type and forgets pay():

class Payment:
    def __init__(self, amount):
        self.amount = amount
    def pay(self):
        raise NotImplementedError("each payment type must define pay()")

class Coupon(Payment):
    pass

print(Coupon(50).pay())

Output:

Traceback (most recent call last):
  File "/tmp/tmppiu36d_f/main.py", line 10, in <module>
    print(Coupon(50).pay())
          ~~~~~~~~~~~~~~^^
  File "/tmp/tmppiu36d_f/main.py", line 5, in pay
    raise NotImplementedError("each payment type must define pay()")
NotImplementedError: each payment type must define pay()

A clear message instead of a silent wrong answer. (Python's abc module can enforce this even earlier, when the object is created; we'll meet it in the design patterns episode.)

Try it: add a Wallet payment that gives 1% cashback.

Practice

1. A Vehicle base class with name and fare(km) that returns km * 10. A Bike child charges km * 5; an AutoRickshaw child charges 30 + km * 12. Bill a list of vehicles for 4 km in one loop.

Solution
class Vehicle:
    def __init__(self, name):
        self.name = name
    def fare(self, km):
        return km * 10

class Bike(Vehicle):
    def fare(self, km):
        return km * 5

class AutoRickshaw(Vehicle):
    def fare(self, km):
        return 30 + km * 12

for v in [Vehicle("Cab"), Bike("Rapido"), AutoRickshaw("Auto")]:
    print(v.name, "Rs", v.fare(4))

Output:

Cab Rs 40
Rapido Rs 20
Auto Rs 78

2. A Student class with name and marks. A Monitor child adds a section using super().__init__, and overrides __str__ to add (monitor of B) after the parent's text.

Solution
class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks
    def __str__(self):
        return f"{self.name}: {self.marks}"

class Monitor(Student):
    def __init__(self, name, marks, section):
        super().__init__(name, marks)
        self.section = section
    def __str__(self):
        return super().__str__() + f" (monitor of {self.section})"

print(Student("Ravi", 78))
print(Monitor("Asha", 91, "B"))

Output:

Ravi: 78
Asha: 91 (monitor of B)

3. Without running it, predict the output. Then run it.

class A:
    def hello(self):
        return "A"

class B(A):
    pass

class C(B):
    def hello(self):
        return "C+" + super().hello()

print(C().hello(), B().hello(), C.__mro__[1].__name__)
Answer

Output:

C+A A B

C.hello runs first and calls super().hello(), the next class in the MRO that has hello: B doesn't, so A's runs. B().hello() is inherited from A. C.__mro__ is (C, B, A, object), so index 1 is B.

4. Write a function total_bill(people, amount) that works for any list of objects with a bill() method (duck typing) and returns the sum. Test it with a Customer, a Staff and a Company.

Solution
class Customer:
    def __init__(self, name):
        self.name = name
    def bill(self, amount):
        return amount + 5

class Staff(Customer):
    def bill(self, amount):
        return amount // 2

class Company:
    def bill(self, amount):
        return amount + amount * 18 // 100

def total_bill(people, amount):
    return sum(p.bill(amount) for p in people)

print(total_bill([Customer("Ravi"), Staff("Raju"), Company()], 200))

Output:

541

205 + 100 + 236 = 541.

Quick quiz

1. The video's quiz: what does this print?

class Tea:
    def make(self):
        return "plain"
    def serve(self):
        return "cup of " + self.make()

class Masala(Tea):
    def make(self):
        return "masala"

print(Masala().serve(), Tea().serve())
Answer

Output:

cup of masala cup of plain

serve() is only written in Tea, but inside it self.make() starts the search from the actual object. For a Masala object, Masala.make wins. This is polymorphism working inside the parent's own code.

2. True or false: a child class must define its own __init__.

Answer

False. If the child has no __init__, the parent's is inherited (like Staff above). Define one only when the child needs extra setup, and then call super().__init__(...).

3. What is printed?

class Customer:
    pass

class VIPCustomer(Customer):
    pass

print(issubclass(VIPCustomer, Customer), issubclass(Customer, VIPCustomer), issubclass(Customer, object))
Answer

Output:

True False True

Every class inherits from object.

Interview questions

  1. What is inheritance? A way to create a new class (child) from an existing one (parent): the child gets all the parent's attributes and methods and can add or change behaviour. It models an "is a" relationship (a VIP is a customer) and removes duplicated code.
  2. What is method overriding? Defining a method in the child with the same name as one in the parent. For child objects, the child's version replaces the parent's.
  3. What does super() do? It returns a proxy to the next class in the MRO, so you can call the parent's version of a method, most often super().__init__(...) to run the parent's setup before adding your own.
  4. What is the MRO? The method resolution order: the order in which Python searches classes for an attribute (child, then parents, ending with object). It's in Class.__mro__ and, for multiple inheritance, is computed with the C3 linearization algorithm.
  5. Does Python support multiple inheritance? Yes: class C(A, B):. The MRO decides which parent's method wins; super() follows the MRO, which makes cooperative multiple inheritance possible.
  6. What is polymorphism? Using one interface (the same method call) with objects of different types, each responding in its own way, e.g. c.bill(200) for customers, VIPs and staff.
  7. What is duck typing? Python's approach of caring about what an object can do (its methods), not its class. Any object with a bill() method can be billed.
  8. isinstance() vs type() ==? isinstance(obj, Customer) is also True for subclasses; type(obj) == Customer is only true for that exact class. Prefer isinstance (and prefer polymorphism over either).
  9. Why raise NotImplementedError in a base method? To mark a method that every subclass must override; calling it without overriding fails loudly instead of returning a wrong result. The abc module (ABC, @abstractmethod) enforces it at object creation.
  10. Inheritance vs composition? Inheritance is "is a"; composition is "has a" (a Khata has customers). Prefer composition when the relationship isn't truly "is a"; deep inheritance trees become hard to change.

Glossary

Term Meaning Example
Inheritance Creating a class from an existing class so it reuses its attributes and methods class VIPCustomer(Customer):
Parent / base class / superclass The class being inherited from Customer
Child / derived class / subclass The class that inherits VIPCustomer
"Is a" relationship What inheritance models: every child object is also a parent object a VIP is a customer
Overriding Redefining a parent's method in the child, replacing it for child objects def bill(self, amount): in Staff
super() Gives access to the parent's version of a method super().__init__(name)
object The built-in top parent of every Python class VIPCustomer.__mro__[-1]
MRO (method resolution order) The order Python searches classes for a method VIPCustomer → Customer → object
__mro__ The class attribute holding the MRO as a tuple VIPCustomer.__mro__
isinstance() True if an object is an instance of a class or any of its subclasses isinstance(asha, Customer) → True
issubclass() True if one class inherits from another issubclass(VIPCustomer, Customer)
Polymorphism One method call, many behaviours, depending on the object c.bill(200) in a loop
Duck typing Using an object based on its methods, not its class any object with bill()
NotImplementedError An exception meaning "a subclass must provide this" raise NotImplementedError(...)
Base class (abstract idea) A parent meant only to be inherited from, not used directly Payment
Multiple inheritance A class with more than one parent class C(A, B):
Composition Building a class that has other objects instead of inheriting a Khata holding customers
AttributeError Using an attribute or method an object doesn't have Supplier(...).bill(200)
TypeError Wrong arguments, e.g. a missing required argument super().__init__() with no name
GST Goods and Services Tax, added to a bill in India amount * 18 // 100
UPI India's instant phone payment system UPI(250, "asha@okbank")
Khata A shop's credit book khata = [Customer(...), ...]

Summary

  • Copy-pasted classes drift apart: a change made in one copy is silently missing from the other.
  • class Child(Parent): inherits every attribute and method of the parent.
  • A child method with the same name overrides (replaces) the parent's.
  • super() runs the parent's version: super().__init__(...) for setup, super().bill(...) to extend a method. Pass on the arguments the parent needs.
  • Python searches child → parent → object: the MRO. isinstance checks the whole family.
  • Polymorphism: one call (c.bill(200)) works for many types, so loops never need if type(...) chains.
  • Duck typing: any object with the right method fits, inheritance or not; a missing method is an AttributeError at call time.
  • A base method that raises NotImplementedError forces every child to provide its own version.

Next episode: OOP part 3. Right now anyone can write asha.credit = -5000 and the class can't stop it. We invent encapsulation, properties, and the dunder methods that make objects work with +, len and print.