Python Inheritance, Method Overriding, and Polymorphism
Introduction
Python inheritance lets a subclass reuse a base class’s methods and specialize selected behavior. An inherited method that calls self.label() can reach an override on the actual object; naming Base.label(self) explicitly chooses a different lookup starting point.
This lesson covers single inheritance and __str__ in PCAP-31-03 objective 4.5, with initializer behavior from 4.6. Object-Oriented Programming carries 34% of the score and 12 of 40 items. You will trace overrides, distinguish type tests, and build readable object representations.
Learning objectives
After this lesson you can:
- Write a derived class and explain what it inherits (methods, class variables, and instance variables created by an inherited
__init__). - Override a method and predict which version is called for a given object.
- Explain polymorphism: one call, several behaviours depending on the object.
- Extend a parent method with
super()instead of rewriting it. - Explain why a child
__init__that does not call the parent's__init__leaves instance variables missing. - Use
isinstance(),issubclass()andtype()and tell them apart. - Write
__str__(and know the role of__repr__) to control how an object is printed.
Base and derived classes
A derived class (also called child or subclass) lists its parent (base class, superclass) in parentheses:
class Vehicle:
wheels = 4
def __init__(self, plate):
self.plate = plate
def describe(self):
return f"{self.plate} with {self.wheels} wheels"
class Truck(Vehicle):
def __init__(self, plate, load):
super().__init__(plate)
self.load = load
class Bike(Vehicle):
wheels = 2
t = Truck("T-1", 7)
b = Bike("B-2")
print(t.describe()) # T-1 with 4 wheels
print(b.describe()) # B-2 with 2 wheels
print(t.wheels, Truck.wheels, Bike.wheels) # 4 4 2Truck defines no describe, yet t.describe() works. For the plain attributes and methods here, lookup checks the instance and follows Truck’s class MRO to Vehicle. Data descriptors and custom attribute hooks require the fuller attribute-access rules. Bike redefines the class variable wheels, so objects of Bike find 2 in their own class before reaching the parent's 4. The method describe is the same function in both cases, but it reads self.wheels, which resolves differently for each object.
An ordinary Python 3 class with no explicit base inherits from object. Because multiple inheritance is supported, ancestry forms a graph rather than necessarily a single tree.
What exactly is inherited
| Element | Inherited by the child? | Remarks |
|---|---|---|
| Methods | Yes | Found through the lookup chain |
| Class variables | Yes | Readable through the child class and its instances |
__init__ |
Yes, if the child does not define its own | A child __init__ replaces it |
| Instance variables | Not inherited as stored class members | They exist when executed code creates them, often in a base initializer |
Private names (__x) |
Name-mangled | Vehicle.__x becomes _Vehicle__x; a child cannot read self.__x by that name |
The most important line is the last-but-one: instance variables do not travel by inheritance. They exist because executed code assigned them, whether in an initializer, another method, or code outside the class.
Overriding methods
A child overrides a method by defining a method with the same name. The child's version is found first, so it wins for objects of the child.
class Base:
def hello(self):
return "base"
def greet(self):
return self.hello() + "!"
class Child(Base):
def hello(self):
return "child"
print(Base().greet()) # base!
print(Child().greet()) # child!greet is defined only in Base. When called on a Child object, self is that Child object, so the expression self.hello() starts its search at Child and finds the overridden version. This behaviour, where the object's real class decides which method runs even inside a parent method, is polymorphism.
Polymorphism removes if type(x) is ... chains. Code that receives any Vehicle calls describe() and each object answers in its own way.
Extending instead of replacing: super()
Often a child wants the parent's behaviour plus something more. super() returns a proxy whose search starts after the lexical class in the current object’s MRO:
class Child2(Base):
def hello(self):
return "child2+" + super().hello()
print(Child2().greet()) # child2+base!super().hello() calls the parent's hello on the same object (self is passed automatically). The same technique is used for constructors, as the Truck example above shows with super().__init__(plate).
You can also name the parent explicitly: Vehicle.__init__(self, plate). It works for a single parent but must be written with self as an explicit argument. Compare multiple inheritance and super before replacing explicit calls mechanically: cooperative lookup can reach a sibling rather than the directly written parent.
The constructor trap
A child that defines __init__ replaces the inherited one. In this example, Vehicle.__init__ is the only code assigning plate. Skipping it leaves that attribute absent. Other code could create an equivalent attribute, so inspect the actual assignments.
class Car(Vehicle):
def __init__(self, brand):
self.brand = brand
c = Car("X")
print(hasattr(c, "plate")) # False
c.describe() # AttributeError: 'Car' object has no attribute 'plate'describe is inherited and found, but it reads self.plate, which was never assigned. The error message names the attribute and the class, and it appears at the point where the missing attribute is read, not where the constructor was written. This confusion between "the method exists" and "the data exists" is a classic exam trap.
Three situations to remember:
Child defines __init__? |
Parent __init__ called? |
Result |
|---|---|---|
| No | Automatically (inherited) | Parent's variables exist |
| Yes | Yes (explicit call) | Both sets of variables exist |
| Yes | No | Only the child's variables exist |
Checking relationships: isinstance, issubclass, type
A type relationship does not establish value equality. Review Python object identity and equality to keep is, ==, and isinstance separate.
print(isinstance(t, Vehicle)) # True
print(type(t) is Vehicle) # False
print(issubclass(Bike, Vehicle)) # True
print(issubclass(Vehicle, Bike)) # False
print(isinstance(t, (Bike, Truck))) # True| Tool | Question | Subclasses count? |
|---|---|---|
type(obj) is Cls |
Is the exact class Cls? |
No |
isinstance(obj, Cls) |
Is obj an instance of Cls or of a class derived from it? |
Yes |
issubclass(A, B) |
Is class A the same as or derived from B? |
Yes |
isinstance accepts a tuple of classes, meaning "any of these". issubclass(A, A) is True. Their second argument can be a class, a tuple of supported class specifications, or a union type in current Python. A string such as "Vehicle" is invalid and raises TypeError.
Remember the direction: a Truck is a Vehicle (child instance, parent class gives True), but a plain Vehicle is not a Truck. isinstance(Vehicle("V"), Truck) is False.
Also recall from lesson 9.2 that Truck.__bases__ shows the direct parent: (<class '__main__.Vehicle'>,), and that sorted(t.__dict__) shows only the instance variables, here ['load', 'plate'].
Readable representations: __str__ and __repr__
When you print() an object, Python calls its __str__ method. If no customized __str__ is supplied, inherited behavior can use __repr__. A plain object with neither customized representation normally displays its type and an identity-style address in CPython.
class P:
def __init__(self, n):
self.n = n
def __str__(self):
return f"P({self.n})"
print(P(1)) # P(1)
print(str(P(3))) # P(3)
print([P(2)]) # [<__main__.P object at 0x...>]Look at the third line. A list shows its elements using __repr__, not __str__. Since P defines only __str__, the list displays the default representation. To control both, define both:
class R:
def __init__(self, n):
self.n = n
def __str__(self):
return f"R({self.n})"
def __repr__(self):
return f"R(n={self.n!r})"
print(R(1)) # R(1)
print([R(2)]) # [R(n=2)]
print(f"{R(3)}") # R(3)
print(repr(R(4))) # R(n=4)__str__ aims at a readable message for users; __repr__ aims at an unambiguous description for developers. If only __repr__ exists, print() falls back to it. Both must return a string; returning a number raises TypeError.
__str__ is inherited like any method. A class Q(P) that adds nothing prints as P(5) because the inherited __str__ is used, and its code runs with self being a Q.
Polymorphism in practice
Suppose a shop prices deliveries. A base class provides a default price and variants change the rule:
class Delivery:
def price(self, weight):
return 5
class Express(Delivery):
def price(self, weight):
return 5 + 2 * weight
class Insured(Delivery):
def price(self, weight):
return super().price(weight) * 2
for o in (Delivery(), Express(), Insured()):
print(type(o).__name__, o.price(3))Output:
Delivery 5
Express 11
Insured 10The dispatch o.price(3) relies on a shared method name; type(o).__name__ is used only to label the output. Express replaces the rule completely, whereas Insured reuses the parent's result and doubles it. Adding a fourth variant requires no change in the loop.
Worked example: two delivery strategies behind one interface
Statement. A parcel company ships weights in kilograms. The base class Tariff computes total(weight) as base + rate * weight (with base = 4, rate = 1) and describes itself through __str__. Night overrides only the rate (3) and Fragile calls the parent total and adds a flat fee of 6. Predict the output.
class Tariff:
base = 4
rate = 1
def total(self, weight):
return self.base + self.rate * weight
def __str__(self):
return f"{type(self).__name__}: {self.total(2)}"
class Night(Tariff):
rate = 3
class Fragile(Tariff):
def total(self, weight):
return super().total(weight) + 6
for tariff in (Tariff(), Night(), Fragile()):
print(tariff)Step 1: the loop and print. print(tariff) calls __str__, which exists only in Tariff but is inherited by all three classes.
Step 2: Tariff(). type(self).__name__ is Tariff. self.total(2) runs 4 + 1 * 2 = 6. Line: Tariff: 6.
Step 3: Night(). Night overrides only the class variable rate. Inside the inherited total, self.rate finds 3 in Night first, so 4 + 3 * 2 = 10. Line: Night: 10. No method was overridden: overriding data is enough to change the result.
Step 4: Fragile(). self.total(2) finds Fragile.total first, which calls super().total(2) (that is 4 + 1 * 2 = 6) and adds 6: 12. Line: Fragile: 12.
Tariff: 6
Night: 10
Fragile: 12Why other readings fail. Predicting Night: 6 forgets that self.rate is looked up starting from the object's real class. Predicting Fragile: 6 ignores that the child's total is called by the parent's __str__; predicting Fragile: 18 applies the fee twice, as if super().total were itself overridden. Printing Tariff for all three lines would mean using a literal class name instead of type(self).__name__.
Designing a base class that children can specialise
Inheritance is worth using when the relationship is truly "is a": a Truck is a Vehicle, an Express delivery is a Delivery. When the relationship is "has a" (a Car has an Engine), the usual solution is to store an object in an instance variable, not to inherit. The exam does not ask you to choose a design, but it does show hierarchies, and recognising the intent helps you read them.
Three habits make a base class easy to extend:
- Put shared data and behaviour in the parent, and only the differences in the children.
- Give the parent a sensible default for the method children are expected to override, so that a child which forgets it still works. A parent can also raise
NotImplementedErrorto say "children must provide this". - Read configuration through
self, asTariff.totaldoes withself.rate, so a child can change behaviour by redefining a simple class variable.
class Report:
title = "Generic"
def render(self):
raise NotImplementedError("children must implement render")
class SalesReport(Report):
title = "Sales"
def render(self):
return f"[{self.title}] 42 orders"
print(SalesReport().render()) # [Sales] 42 orders
try:
Report().render()
except NotImplementedError as e:
print("error:", e) # error: children must implement renderNotImplementedError is a built-in exception derived from RuntimeError. Calling the parent's method directly fails with a clear message, whereas a forgetful child would otherwise silently inherit a meaningless result.
Common pitfalls and exam tips
| Pitfall | What happens | Remedy |
|---|---|---|
Child __init__ without calling the parent's |
Parent variables missing, AttributeError later |
Call Parent.__init__(self, ...) or super().__init__(...) |
Expecting type(x) is Parent to be true for a child |
False |
Use isinstance(x, Parent) |
| Confusing method and data | Method inherited but data absent | Check which __init__ ran |
| Believing the parent method calls the parent's version of other methods | self.method() starts from the real class |
Trace with the object's class |
Forgetting self when calling Parent.method(self) |
TypeError for a missing argument |
Pass self explicitly, or use super() |
__str__ returning a non-string |
TypeError |
Return str(...) or an f-string |
Expecting lists to show __str__ |
Lists use __repr__ |
Define __repr__ as well |
Reversing issubclass arguments |
A distinct base is not a subclass of its child | Read the relationship from child to ancestor |
Exam tip. To predict an overridden call, ask: "What is the class of self?" Then search from that class upward. For a normal self.method() call, dispatch uses that object. An explicit class lookup or super() has a different starting point.
Exam tip. When a child redefines a class variable, parent methods that read self.variable see the child's value.
Exam tip. isinstance(x, object) is always True, and issubclass(C, object) is always True for every class C.
End-of-lesson case study
Situation. A support tool has a Ticket class with __init__(self, ident) storing self.ident, and summary() returning "#" + str(self.ident). A developer writes UrgentTicket(Ticket) that adds a level and overrides summary() to add the level. Predict the output and fix any problem.
class Ticket:
def __init__(self, ident):
self.ident = ident
def summary(self):
return "#" + str(self.ident)
class UrgentTicket(Ticket):
def __init__(self, level):
self.level = level
def summary(self):
return Ticket.summary(self) + " urgent " + str(self.level)
items = [Ticket(7), UrgentTicket(2)]
print(items[0].summary())
print(isinstance(items[1], Ticket))
print(items[1].summary())Solution, commented. The first print gives #7. The second is True: an UrgentTicket is a Ticket. The third raises AttributeError: 'UrgentTicket' object has no attribute 'ident'. The child __init__ replaced the parent's one, so ident was never assigned, although Ticket.summary(self) was found and called correctly. Output before the crash is therefore #7 then True.
A correct design passes both values and calls the parent's initialiser first:
class UrgentTicket(Ticket):
def __init__(self, ident, level):
super().__init__(ident)
self.level = levelWith UrgentTicket(7, 2) the summary is #7 urgent 2. Note the cost of the explicit parent call in summary: Ticket.summary(self) hard-codes the parent's name, while super().summary() follows the hierarchy if the parent changes.
Key terms
- Base class / derived class: the parent and the class built from it.
- Override: redefine an inherited method in the child with the same name.
- Polymorphism: the same call producing different behaviour depending on the object's class.
super(): a proxy that searches the object’s MRO after the lexical class, finding the next applicable implementation.isinstance()/issubclass(): tests of object-to-class and class-to-class relationships.__str__/__repr__: special methods returning the readable and the developer-oriented string.
Summary checklist
- I can predict which method runs when parent and child define the same name.
- I know a child
__init__replaces the parent's and must call it to keep the parent's variables. - I can trace a parent method that calls
self.other()using the real class ofself. - I know when a class variable override changes parent behaviour.
- I can distinguish
type(x) is C,isinstance(x, C)andissubclass(A, B). - I can write
__str__and explain why lists use__repr__. - I can use
super()to extend rather than rewrite a method.
Official sources
- Python Institute, PCAP-31-03 exam syllabus (4.5 inheritance and representations, 4.6 initialization): https://pythoninstitute.org/pcap-31-03-exam-syllabus (opens in a new tab)
- Python documentation, tutorial on inheritance: https://docs.python.org/3.14/tutorial/classes.html#inheritance (opens in a new tab)
- Python documentation,
super()andisinstance(): https://docs.python.org/3.14/library/functions.html (opens in a new tab) - Python documentation,
__str__and__repr__: https://docs.python.org/3.14/reference/datamodel.html#object.__str (opens in a new tab)__
