Lesson 55 of 70 – Python Abstraction
79%

Python Abstraction

Abstraction is an important concept of Object-Oriented Programming (OOP). It means hiding unnecessary implementation details and showing only the essential features of an object.

For example, when you use a mobile phone, you press a button to make a call. You do not need to know all the internal processes involved in connecting the call.

Note: In Python, abstraction is commonly implemented using the abc module and abstract base classes.
What is Abstraction?

Abstraction means exposing only the important functionality while hiding the internal implementation details.

It helps programmers focus on what an object does instead of how it does it.

class Car:

    def start(self):
        print("Car started")


car = Car()

car.start()
Output:
Car started

The user only needs to know that start() starts the car. The internal implementation can remain hidden.

Why is Abstraction Used?

Abstraction provides several benefits:

  • Hides unnecessary implementation details.
  • Makes programs easier to understand.
  • Reduces complexity.
  • Provides a common interface.
  • Makes code easier to maintain.
  • Helps organize large applications.
  • Allows different classes to provide their own implementation.
Real-Life Example of Abstraction

Consider an ATM machine.

You can perform operations such as:

  • Withdraw money
  • Deposit money
  • Check balance

You do not need to know the internal banking operations performed by the ATM.

Example: You select "Withdraw Cash" and provide the amount. The ATM handles the internal process.
Abstraction in Python

Python provides the abc module for creating abstract base classes.

The two commonly used components are:

  • ABC
  • abstractmethod
from abc import ABC, abstractmethod

A class can inherit from ABC and define abstract methods using @abstractmethod.

Abstract Base Class

An Abstract Base Class (ABC) is a class designed to define a common interface for its subclasses.

from abc import ABC, abstractmethod

class Animal(ABC):

    @abstractmethod
    def sound(self):
        pass

Here, Animal is an abstract base class.

Abstract Method

An abstract method is a method that is declared in an abstract base class but is intended to be implemented by subclasses.

from abc import ABC, abstractmethod

class Animal(ABC):

    @abstractmethod
    def sound(self):
        pass


class Dog(Animal):

    def sound(self):
        print("Dog barks")


dog = Dog()

dog.sound()
Output:
Dog barks
Importing ABC and abstractmethod

We import the required components from Python's built-in abc module.

from abc import ABC, abstractmethod

Here:

  • ABC is used as a base class for abstract classes.
  • abstractmethod marks a method as abstract.
Creating an Abstract Class
from abc import ABC

class Vehicle(ABC):

    pass

The Vehicle class inherits from ABC.

An abstract class can contain abstract methods as well as regular methods.

Creating an Abstract Method
from abc import ABC, abstractmethod

class Vehicle(ABC):

    @abstractmethod
    def start(self):
        pass

The start() method is an abstract method.

A concrete subclass should provide an implementation for this method before its objects can normally be created.

Implementing an Abstract Method
from abc import ABC, abstractmethod

class Vehicle(ABC):

    @abstractmethod
    def start(self):
        pass


class Car(Vehicle):

    def start(self):
        print("Car starts with a key")


class Bike(Vehicle):

    def start(self):
        print("Bike starts with a button")


car = Car()
bike = Bike()

car.start()
bike.start()
Output:
Car starts with a key
Bike starts with a button

Both classes follow the same interface, but each class provides its own implementation.

Cannot Normally Create an Object of an Abstract Class

A class containing an unimplemented abstract method cannot normally be instantiated.

from abc import ABC, abstractmethod

class Animal(ABC):

    @abstractmethod
    def sound(self):
        pass


animal = Animal()
Result:

Python raises a TypeError because Animal still has an abstract method.

Subclass Must Implement Abstract Method
from abc import ABC, abstractmethod

class Animal(ABC):

    @abstractmethod
    def sound(self):
        pass


class Dog(Animal):

    pass


dog = Dog()
Result:

This also raises a TypeError because Dog has not implemented the abstract method sound().

Abstract Class with Multiple Abstract Methods

An abstract class can contain multiple abstract methods.

from abc import ABC, abstractmethod

class Shape(ABC):

    @abstractmethod
    def area(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass

A concrete subclass should implement both methods.

Implementing Multiple Abstract Methods
from abc import ABC, abstractmethod

class Shape(ABC):

    @abstractmethod
    def area(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass


class Rectangle(Shape):

    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

    def perimeter(self):
        return 2 * (self.length + self.width)


rectangle = Rectangle(10, 5)

print(rectangle.area())
print(rectangle.perimeter())
Output:
50
30
Abstract Class with Normal Method

An abstract class can contain both abstract methods and normal methods.

from abc import ABC, abstractmethod

class Animal(ABC):

    def eat(self):
        print("Animal eats food")

    @abstractmethod
    def sound(self):
        pass


class Dog(Animal):

    def sound(self):
        print("Dog barks")


dog = Dog()

dog.eat()
dog.sound()
Output:
Animal eats food
Dog barks
Abstraction and Implementation

The abstract class defines what functionality a subclass must provide. The subclass decides how that functionality is implemented.

from abc import ABC, abstractmethod

class Payment(ABC):

    @abstractmethod
    def pay(self, amount):
        pass


class CashPayment(Payment):

    def pay(self, amount):
        print("Paid", amount, "using cash")


class CardPayment(Payment):

    def pay(self, amount):
        print("Paid", amount, "using card")


cash = CashPayment()
card = CardPayment()

cash.pay(1000)
card.pay(2000)
Output:
Paid 1000 using cash
Paid 2000 using card
Abstraction with Inheritance

Abstraction is frequently combined with inheritance. The abstract base class defines a common structure, while child classes provide specific implementations.

from abc import ABC, abstractmethod

class Employee(ABC):

    @abstractmethod
    def calculate_salary(self):
        pass


class FullTimeEmployee(Employee):

    def calculate_salary(self):
        print("Calculating full-time salary")


class PartTimeEmployee(Employee):

    def calculate_salary(self):
        print("Calculating part-time salary")


employee1 = FullTimeEmployee()
employee2 = PartTimeEmployee()

employee1.calculate_salary()
employee2.calculate_salary()
Output:
Calculating full-time salary
Calculating part-time salary
Abstraction vs Encapsulation
Abstraction Encapsulation
Hides unnecessary implementation details. Bundles data and methods together.
Focuses on what an object does. Focuses on controlling access to data.
Often implemented using abstract classes and methods. Often implemented using naming conventions, methods and properties.
Reduces complexity for the user. Helps protect and control internal state.
Abstraction vs Inheritance
Abstraction Inheritance
Hides implementation details. Allows a class to inherit features from another class.
Defines a common interface. Creates a parent-child relationship.
Can use abstract methods. Can reuse and extend existing functionality.
Using Abstract Classes in Real Projects

Abstract classes are useful when several classes should follow the same interface but need different implementations.

Common examples include:

  • Payment systems
  • Banking applications
  • Vehicle management systems
  • Employee management systems
  • Shape and graphics applications
  • Database systems
  • Notification systems
  • File storage systems
Complete Abstraction Example
from abc import ABC, abstractmethod

class Notification(ABC):

    @abstractmethod
    def send(self, message):
        pass


class EmailNotification(Notification):

    def send(self, message):
        print("Email:", message)


class SMSNotification(Notification):

    def send(self, message):
        print("SMS:", message)


email = EmailNotification()
sms = SMSNotification()

email.send("Welcome to our website")
sms.send("Your OTP is 1234")
Output:
Email: Welcome to our website
SMS: Your OTP is 1234

The abstract class defines the send() interface, while each subclass decides how the message is sent.

Important Rules of Abstract Classes
  • Use ABC as the base class for an abstract base class.
  • Use @abstractmethod to declare an abstract method.
  • An abstract method is intended to be implemented by concrete subclasses.
  • A class with unimplemented abstract methods cannot normally be instantiated.
  • A subclass must implement inherited abstract methods to become instantiable.
  • An abstract class can contain normal methods as well.
  • An abstract class can contain multiple abstract methods.
Key Points
  • Abstraction means hiding unnecessary implementation details.
  • It focuses on what an object does rather than how it does it.
  • Python provides the built-in abc module for abstraction.
  • ABC is used to create abstract base classes.
  • @abstractmethod is used to define abstract methods.
  • Abstract classes can contain both abstract and normal methods.
  • Concrete subclasses provide implementations for abstract methods.
  • Abstraction helps reduce complexity and creates a common interface.

🧠 Quick Quiz

Question: Which module is commonly used to implement abstraction in Python?