Skip to content

Module 11 · Object-Oriented Programming — topic 16 of 25

Single inheritance

A class with exactly one parent: the most common form of inheritance, how attribute and method lookup walks up the chain, and designing a clean parent-child pair.

Beginner 8 min read·Lesson 173 of 306 in Python Programming

Learning objectives

  • Build a parent-child class pair
  • Trace method lookup from child to parent
  • Decide what belongs in the parent and what in the child

Definition

Single inheritance is when a class derives from exactly one parent class. Attribute and method lookup checks the child first and then the parent.

Introduction

Most inheritance in practice is single inheritance: Shape → Circle, Account → SavingsAccount, Exception → ValueError. One general parent, one specialised child.

Why it matters

Designing the split correctly — shared behaviour in the parent, specific behaviour in the child — makes adding new kinds of objects easy.

Detailed explanation

With class Circle(Shape), circle.method() looks in Circle first, then Shape, then object.

The parent should hold everything common to all children: shared attributes, shared methods and default behaviour.

The child adds what is specific and overrides defaults that don't fit.

Class.__mro__ (method resolution order) shows the exact lookup chain.

A good test: can a child be used everywhere the parent is expected without surprises? If not, the inheritance is probably wrong (the Liskov substitution principle).

If a child doesn't define __init__ at all, the parent's __init__ is used automatically, so the child is created with exactly the same arguments as the parent. Define __init__ in the child only when it needs extra data, and then call super().__init__ first.

Syntax

Python
class Shape:
def __init__(self, name):
self.name = name
def describe(self):
return f"{self.name} with area {self.area():.2f}"
def area(self):
return 0.0
class Circle(Shape):
def __init__(self, r):
super().__init__("circle")
self.r = r
def area(self):
return 3.14159 * self.r ** 2
  • One parent class.
  • Lookup: child → parent → object.
  • Shared logic in the parent.

Code examples

Lookup goes up the chain

Python
class Shape:
def __init__(self, name):
self.name = name
def describe(self):
return f"{self.name} with area {self.area():.2f}"
def area(self):
return 0.0
class Circle(Shape):
def __init__(self, r):
super().__init__("circle")
self.r = r
def area(self):
return 3.14159 * self.r ** 2
c = Circle(2)
print(c.describe())
print([cls.__name__ for cls in Circle.__mro__])
Output
circle with area 12.57
['Circle', 'Shape', 'object']

Default behaviour in the parent

Python
class Notification:
channel = "generic"
def send(self, msg):
return f"[{self.channel}] {msg}"
class Email(Notification):
channel = "email"
class Sms(Notification):
channel = "sms"
def send(self, msg):
return super().send(msg[:20]) # SMS messages are short
for n in [Email(), Sms()]:
print(n.send("Your order #1042 has been shipped today"))
Output
[email] Your order #1042 has been shipped today
[sms] Your order #1042 has

More examples

A small hierarchy for shapes

Python
class Shape:
def area(self):
raise NotImplementedError
def perimeter(self):
raise NotImplementedError
def describe(self):
return f"{type(self).__name__}: area {self.area():.2f}, perimeter {self.perimeter():.2f}"
class Rectangle(Shape):
def __init__(self, w, h):
self.w, self.h = w, h
def area(self):
return self.w * self.h
def perimeter(self):
return 2 * (self.w + self.h)
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
for s in [Rectangle(3, 4.5), Square(2)]:
print(s.describe())
print(isinstance(Square(1), Rectangle))
Output
Rectangle: area 13.50, perimeter 15.00
Square: area 4.00, perimeter 8.00
True

Step-by-step explanation

  • Shape defines describe once, using area and perimeter that children must provide.
  • Rectangle implements both; Square only changes how it is constructed.
  • Square inherits area and perimeter from Rectangle, which inherits describe from Shape.

Expected output

Running “A small hierarchy for shapes” prints exactly:

TextOutput
Rectangle: area 13.50, perimeter 15.00
Square: area 4.00, perimeter 8.00
True

Practical applications

  • ValueError(Exception), FileNotFoundError(OSError).
  • Custom widgets subclassing a framework's base widget.

Best practices

  • Put shared behaviour in the parent, specifics in the child.
  • Check substitutability before inheriting.
  • Inspect __mro__ when lookup is unclear.

Common mistakes

Child that breaks the parent's promises

Avoid

class ReadOnlyList(list):
def append(self, x):
raise Exception # surprises code expecting a list

Prefer

Use composition or a tuple.

A child should be usable wherever the parent is expected.

Important notes

  • NotImplementedError in a base method is a simple way to say 'subclasses must provide this'; abstract base classes (later) make it enforced.

Key takeaways

  • Single inheritance: one parent per class.
  • Lookup walks child → parent → object.
  • Children should be substitutable for parents.

Try it yourself

  1. 1
    Write a Vehicle parent with a describe method and two children that override max_speed.
  2. 2
    Print the __mro__ of ValueError and explain it.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

16 questions cover the “Object-Oriented Programming” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module