Python Abstraction
Table of Contents
Description
Abstraction is one of the four pillars of Object-Oriented Programming (OOP). It means hiding complex implementation details and showing only the necessary features of an object.
In Python, abstraction is primarily achieved using:
Abstract Base Classes (ABCs) via the abc module.
Encapsulation + Interfaces — to enforce structure and limit access.
It helps to reduce complexity, increase code reusability, and provide a clear interface for users of your code.
Prerequisites
- Basic understanding of Classes and Objects
- Inheritance
- Functions and Methods
- Concept of OOP principles
Examples
Here's a simple program in Python:
✅ 1. Using Abstract Base Classes from abc import ABC, abstractmethod # Creating an abstract base class class Animal(ABC): @abstractmethod def sound(self): # Abstract method with no body pass def breathe(self): # Concrete method print("Breathing...") # Subclass inheriting from Animal class Dog(Animal): def sound(self): # Overriding abstract method print("Bark") class Cat(Animal): def sound(self): # Overriding abstract method print("Meow") # Creating instances d = Dog() c = Cat() d.sound() # Output: Bark c.sound() # Output: Meow d.breathe() # Output: Breathing... ✅ 2. Trying to instantiate an abstract class (throws error) a = Animal() # ❌ Error: Can't instantiate abstract class ✅ 3. Abstraction with Partial Implementation from abc import ABC, abstractmethod class Vehicle(ABC): @abstractmethod def start(self): pass @abstractmethod def stop(self): pass class Car(Vehicle): def start(self): print("Car started") def stop(self): print("Car stopped") c = Car() c.start() # Output: Car started c.stop() # Output: Car stopped
Real-World Applications
Banking Systems: Abstracting transaction operations while hiding internal validations
Machine Learning Models: Defining a base Model class with train() and predict() methods that must be implemented by every specific model.
Device Drivers: Unified interface for interacting with different types of hardware.
Web Development: Abstract controllers and APIs that define structure but allow customization.
Where topic Can Be Applied
Software architecture design
API and SDK development
Plugin-based systems
Backend frameworks
Robotics and hardware abstraction layers
Game engines (abstract base for characters, inputs, physics, etc.)
Resources
Topic video source
A comprehensive video
Python pdf
pdf on topic
Interview Questions
What is abstraction in Python?
How is abstraction different from encapsulation?
What are abstract base classes (ABCs) in Python?
How do you declare and use abstract methods?
Can we create objects of abstract classes?
What happens if you forget to implement an abstract method in a subclass?
Why is abstraction useful in large-scale software design?
How does Python handle interfaces using abstract classes?