Inheritance and polymorphism in Python
Clear, exam-oriented notes on Python inheritance and polymorphism with definitions, syntax, MRO, super(), multiple inheritance, ABCs, duck typing, operator overloading, examples, and pitfalls.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Engineers use inheritance and polymorphism to reuse code safely and to write flexible systems where different objects can be used through a common interface. This reduces duplication, makes maintenance easier, and supports scalable designs such as plugin architectures, device drivers, and testable components.
Key ideas
Inheritance: Inheritance is the mechanism by which a class (child/subclass/derived class) acquires properties and behavior from another class (parent/superclass/base class). Exact statement: In Python, inheritance is declared by listing base classes in parentheses in the class definition, and attribute/method lookup in a subclass follows the Method Resolution Order (MRO) across the inheritance graph.
Single inheritance: A subclass inherits from exactly one base class. Assumption: The base class is either user-defined or built-in and compatible.
Multiple inheritance: A subclass inherits from more than one base class. Exact statement: Python supports multiple inheritance using C3 linearization to compute a consistent MRO; the subclass’s attribute lookup follows this linearized order.
Method Resolution Order (MRO): MRO is a deterministic linear order of classes that Python follows to resolve attribute/method lookup. Exact statement: For new-style classes, Python uses C3 linearization to produce an MRO that preserves local precedence order and monotonicity. Derivation students may show: Given class D(B, C), MRO(D) = D + merge(MRO(B), MRO(C), [B, C]). The merge picks the first head that is not in any other list’s tail; repeat until lists are empty.
Override (method overriding): Overriding is defining in a subclass a method with the same name as in the base class to change behavior. Assumption: The names match and the subclass method is intended to replace or extend the base behavior.
super():
super()is a built-in that returns a proxy to delegate method calls to the next class in the MRO. Exact statement:super()with no arguments inside a method defined in a class body refers tosuper(CurrentClass, self), and calling a method on it dispatches to the next class in MRO. Assumption: The method is defined withself(for instance methods) and participates in cooperative multiple inheritance if each class callssuper().Cooperative multiple inheritance: A design pattern where each class in a multiple-inheritance hierarchy calls
super()so that all relevant methods in the MRO run exactly once.Polymorphism: Polymorphism is the ability to use a single interface to represent different underlying forms (data types). Exact statement: In Python, polymorphism arises through subtype polymorphism (inheritance and overriding), duck typing (structural behavior), and ad-hoc polymorphism (operator/function behavior dependent on types via special methods).
Duck typing: Duck typing is a form of polymorphism where an object’s suitability is determined by the presence of certain methods/attributes rather than its type. Statement: “If it walks like a duck and quacks like a duck, treat it as a duck.” Assumption: Methods used actually exist; otherwise
AttributeErroroccurs at runtime.Abstract Base Class (ABC): An ABC is a class that cannot be instantiated and defines one or more abstract methods that subclasses must implement. Exact statement: In Python, importing from
abc, decorating methods with@abstractmethod, and subclassingABCmarks abstract methods; attempting to instantiate a class with unimplemented abstract methods raisesTypeError.Special methods (dunder methods): Methods with names surrounded by double underscores (e.g.,
__str__,__add__) that implement language-level behavior such as printing, arithmetic, iteration, or context management.Operator overloading: Redefining how operators (like
+,==) behave for user-defined classes by implementing corresponding special methods. Exact statement: Python resolves an operator call likea + basa.__add__(b)and, if NotImplemented, triesb.__radd__(a)following MRO and type rules.isinstance and issubclass:
isinstance(obj, ClassOrTuple)returns True if the class (or any class in the tuple) appears in the MRO of obj’s class (or obj’s class is registered as a virtual subclass of that ABC).issubclass(Sub, Super)returns True if Super is in MRO of Sub (or Sub is registered as a virtual subclass of Super when Super is an ABC).Liskov Substitution Principle (LSP): Formal definition: If S is a subtype of T, then objects of type T may be replaced with objects of type S without altering any desirable properties of the program (correctness, task performed). Assumption: Subtypes honor the contracts (preconditions no stronger, postconditions no weaker) of base types. In Python, runtime contracts are not enforced by the interpreter, so this is a design guideline.
Diagram to draw and label (for an exam answer):
- Draw a simple class hierarchy box diagram: A rectangle labeled “Animal (base)”, arrows pointing down to two rectangles “Dog (derived)” and “Cat (derived)”. For multiple inheritance, draw “Walker” and “Swimmer” boxes above, with arrows to “AmphibiousRobot (derived)”. Label arrows as “inherits from”. Optionally annotate with method names: Animal: speak(), Dog: speak() overrides, Cat: speak() overrides; Walker: move() (walking), Swimmer: move() (swimming); AmphibiousRobot: move() calls super().move() style.
Typical MRO derivation students may be asked to show (step-by-step):
- Given classes:
class A: ...class B(A): ...class C(A): ...class D(B, C): ... - Known MROs: MRO(A) = [A, object]; MRO(B) = [B] + merge([A, object], [A]) = [B, A, object]; MRO(C) = [C, A, object]
- Compute MRO(D): merge([B, A, object], [C, A, object], [B, C])
- Heads: B, C, B. B is not in any tail (tails are [A, object], [A, object], [C]); select B.
- Remove B; lists become [A, object], [C, A, object], [C]
- Heads: A, C, C. C not in any tail (tails [object], [A, object], []); select C.
- Remove C; lists become [A, object], [A, object], []
- Heads: A, A. A not in any tail (tails [object], [object]); select A.
- Remove A; lists become [object], [object]
- Heads: object, object. object not in any tail ([]), select object.
- Remove object; lists empty. So MRO(D) = [D, B, C, A, object].
Formulas
class Derived(Base1, Base2):— Multiple inheritance. Left-to-right order affects MRO.def method(self, ...):— Instance method. First parameter is the instance.super().method(args)— Call next implementation in MRO. Use inside methods to cooperate with base classes.isinstance(obj, ClassOrTuple)— True if ClassOrTuple (or any element of the tuple) appears in obj.class.mro, or if obj’s class is a registered virtual subclass of that ABC.issubclass(Sub, Super)— True if Super is in MRO of Sub, or Sub is a registered virtual subclass.from abc import ABC, abstractmethod— Import for abstract base classes.class X(ABC):— Define an abstract base class.@abstractmethod— Decorate methods that must be overridden to instantiate.def __str__(self): ...— Special method for string conversion with str().def __add__(self, other): ...— Special method for + operator overloading.def __init__(self, ...): super().__init__(...)— Constructor chaining with super().object.__init__(self)— Base initializer if needed (rare; prefer super()).Class.__mro__orClass.mro()— Inspect method resolution order.
Worked examples
Example 1: Single inheritance, overriding, and super() Complete program:
class Account:
def __init__(self, owner, balance=0.0):
self.owner = owner
self.balance = float(balance)
def describe(self):
return f"Account(owner={self.owner}, balance={self.balance:.2f})"
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
class SavingsAccount(Account):
def __init__(self, owner, balance=0.0, rate=0.04):
super().__init__(owner, balance) # call base initializer
self.rate = float(rate)
def describe(self): # override
base = super().describe() # extend base behavior
return base + f", rate={self.rate:.2%}"
def add_interest(self):
interest = self.balance * self.rate
self.balance += interest
return interest
if __name__ == "__main__":
s = SavingsAccount("Asha", 1000.0, 0.05)
print(s.describe())
s.deposit(500)
earned = s.add_interest()
print(f"Interest added: {earned:.2f}")
print(s.describe())
Sample input:
- (no input) Exact output:
Account(owner=Asha, balance=1000.00), rate=5.00%
Interest added: 75.00
Account(owner=Asha, balance=1575.00), rate=5.00%
Example 2: Multiple inheritance with cooperative super() and MRO Complete program:
class Logged:
def __init__(self, *args, **kwargs):
print("Logged.__init__ start")
super().__init__(*args, **kwargs)
print("Logged.__init__ end")
def save(self):
print("Logged.save")
super().save()
class Timestamped:
def __init__(self, *args, **kwargs):
print("Timestamped.__init__ start")
super().__init__(*args, **kwargs)
print("Timestamped.__init__ end")
def save(self):
print("Timestamped.save")
super().save()
class Model:
def __init__(self, *args, **kwargs):
print("Model.__init__")
def save(self):
print("Model.save (final)")
class User(Logged, Timestamped, Model):
def __init__(self, name):
print("User.__init__ start")
super().__init__()
self.name = name
print("User.__init__ end")
def save(self):
print(f"User.save for {self.name}")
super().save()
if __name__ == "__main__":
u = User("Bala")
print("MRO:", [cls.__name__ for cls in User.__mro__])
u.save()
Sample input:
- (no input) Exact output:
User.__init__ start
Logged.__init__ start
Timestamped.__init__ start
Model.__init__
Timestamped.__init__ end
Logged.__init__ end
User.__init__ end
MRO: ['User', 'Logged', 'Timestamped', 'Model', 'object']
User.save for Bala
Logged.save
Timestamped.save
Model.save (final)
Explanation: Each __init__ and save cooperates using super(). Because of the MRO order, each runs exactly once.
Example 3: Polymorphism via duck typing and ABC Complete program:
from abc import ABC, abstractmethod
class Notifier(ABC):
@abstractmethod
def notify(self, message):
pass
class EmailNotifier(Notifier):
def notify(self, message):
print(f"Email: {message}")
class SMSNotifier(Notifier):
def notify(self, message):
print(f"SMS: {message}")
# Duck-typed function: accepts any object with .notify(message)
def send_alert(channel, message):
channel.notify(message)
if __name__ == "__main__":
channels = [EmailNotifier(), SMSNotifier()]
for ch in channels:
send_alert(ch, "Server down!")
# Duck typing: a different class with the right method works too
class Logger:
def notify(self, message):
print(f"LOG: {message}")
send_alert(Logger(), "Recovered")
# isinstance shows ABC relation
print(isinstance(EmailNotifier(), Notifier))
Sample input:
- (no input) Exact output:
Email: Server down!
SMS: Server down!
LOG: Recovered
True
Optional operator overloading mini-snippet (for study):
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v = Vector(1, 2) + Vector(3, 4)
print(v)
Expected output:
Vector(4, 6)
Common mistakes
- Overriding a method but forgetting to return a value or to call
super()when extension is intended, changing behavior unexpectedly. - Assuming Python supports compile-time “method overloading” by defining the same method name multiple times with different parameters; in Python, later definitions overwrite earlier ones. Use default values,
*args,**kwargs, or singledispatch if appropriate. - Misusing
super()outside a class method or passing wrong arguments, leading toRuntimeErrororTypeError. In Python 3, zero-argumentsuper()works only inside methods defined in a class body. - Relying on type instead of behavior (duck typing) and then calling a missing method, causing
AttributeErrorat runtime. - Confusing
isinstanceandissubclass, or expectingisinstanceto work with abstract classes without proper subclassing. - Implementing operator overloading without returning
NotImplementedfor unsupported operand types, breaking symmetric dispatch.
For your exam
- Derivations: Compute MRO for a given class graph step-by-step using the merge algorithm. State assumptions and show each selection of head element until lists are empty.
- Programs: Write class hierarchies showing overriding and
super(). Show multiple inheritance where each class’s method runs exactly once. Show an ABC with one abstract method and a concrete subclass. Provide sample output. - Diagrams: Draw and label a class hierarchy, with arrows from derived to base classes or vice versa (be consistent and label “inherits from”). Mention which methods are overridden.
- Full-marks tips: Use correct syntax, show MRO order explicitly when asked (e.g.,
Class.__mro__), explain whysuper()is used, and demonstrate outputs that match the requested behavior exactly. For theory, mention C3 linearization and LSP by name.
Quick check
- Define polymorphism in Python and name two ways it is achieved.
- Why is
super()preferred over calling a base class directly in multiple inheritance? - What happens if a subclass of an ABC does not implement all abstract methods and you try to instantiate it?
Answers: 1) Polymorphism is using a common interface for different types; achieved via subtype polymorphism (inheritance and overriding) and duck typing (also via operator overloading). 2) super() follows the MRO to ensure each class’s method is called exactly once, enabling cooperative multiple inheritance; direct base calls can skip or duplicate calls. 3) Python raises a TypeError because the class remains abstract until all abstract methods are implemented.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?