Skip to content

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

Abstraction

Hiding complexity behind a simple interface: what abstraction means, separating 'what' from 'how', designing interfaces, and swapping implementations without changing callers.

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

Learning objectives

  • Explain abstraction and how it differs from encapsulation
  • Design a simple interface that hides details
  • Swap implementations behind the same interface

Definition

Abstraction is showing only the essential operations of an object while hiding how they are implemented. Users of the object work with a simple interface and don't need to know the internal details.

Introduction

You drive a car with a steering wheel and pedals without thinking about fuel injection. The controls are the abstraction; the engine's workings are hidden behind them.

Why it matters

Abstraction keeps programs understandable. Each part exposes a small set of meaningful operations, so you can think about one layer at a time and replace implementations safely.

Detailed explanation

Abstraction focuses on what an object does (send an email, save a value); the implementation decides how.

Encapsulation and abstraction work together: encapsulation hides data and protects it, abstraction hides complexity and presents a simple interface.

Good interfaces use names from the problem domain (deposit, publish) rather than from the implementation (update_row, write_socket).

When several implementations share an interface (memory storage, file storage, database storage), callers can switch between them without changes.

Python's built-ins are abstractions too: sorted() works on any iterable without you knowing how it sorts.

Abstract base classes, covered next, are a formal tool for declaring such interfaces.

Abstraction also helps testing: when code depends only on an interface, a simple in-memory implementation can stand in for a real database or network service, so tests run quickly and without external systems.

Syntax

Python
class EmailService:
def send(self, to, subject): # simple public interface
self._connect() # hidden details
return self._format(to, subject)
  • Expose a few meaningful methods.
  • Hide helpers behind _ names.
  • Callers depend on the interface only.

Code examples

A simple interface over hidden steps

Python
class EmailService:
def send(self, to, subject):
self._connect()
msg = self._format(to, subject)
return f"sent: {msg}"
def _connect(self):
self.connected = True
def _format(self, to, subject):
return f"To: {to} | Subject: {subject.strip().title()}"
print(EmailService().send("asha@example.com", " monthly report "))
Output
sent: To: asha@example.com | Subject: Monthly Report

Built-in abstractions

Python
print(sorted("python"), sorted({3, 1, 2}), sorted((5, 4)))
Output
['h', 'n', 'o', 'p', 't', 'y'] [1, 2, 3] [4, 5]

More examples

Swapping implementations

Python
class Storage:
def save(self, key, value):
raise NotImplementedError
def load(self, key):
raise NotImplementedError
class MemoryStorage(Storage):
def __init__(self):
self._data = {}
def save(self, key, value):
self._data[key] = value
def load(self, key):
return self._data.get(key)
class LoggingStorage(Storage):
def __init__(self, inner):
self.inner = inner
self.log = []
def save(self, key, value):
self.log.append(f"save {key}")
self.inner.save(key, value)
def load(self, key):
self.log.append(f"load {key}")
return self.inner.load(key)
def remember_user(store, name):
count = (store.load(name) or 0) + 1
store.save(name, count)
return count
store = LoggingStorage(MemoryStorage())
for n in ["asha", "ravi", "asha"]:
print(n, remember_user(store, n))
print(store.log)
Output
asha 1
ravi 1
asha 2
['load asha', 'save asha', 'load ravi', 'save ravi', 'load asha', 'save asha']

Step-by-step explanation

  • remember_user only uses save and load — the Storage interface.
  • LoggingStorage wraps another storage and records every call, without remember_user noticing.
  • A file or database storage could be plugged in the same way.

Expected output

Running “Swapping implementations” prints exactly:

TextOutput
asha 1
ravi 1
asha 2
['load asha', 'save asha', 'load ravi', 'save ravi', 'load asha', 'save asha']

Practical applications

  • Database drivers share the DB-API interface.
  • Cloud SDKs hide HTTP requests behind methods like upload_file.

Best practices

  • Name methods after what they achieve.
  • Keep public interfaces small.
  • Write calling code against the interface, not a specific class.

Common mistakes

Leaking implementation details

Avoid

service.smtp_socket.write(...)

Prefer

service.send(to, subject)

Callers tied to internals break when the implementation changes.

Important notes

  • Abstraction is a design idea; Python doesn't need special syntax for it.

Key takeaways

  • Abstraction shows what, hides how.
  • Simple interfaces make code easier to use and change.
  • Implementations behind one interface are interchangeable.

Try it yourself

  1. 1
    Add a FileStorage that stores values in a dictionary saved as JSON text and use it with remember_user.
  2. 2
    Design the public interface for a MusicPlayer class without implementing 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