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.
abc module and abstract base classes.
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()
Car started
The user only needs to know that start() starts the car. The internal implementation can remain hidden.
Abstraction provides several benefits:
Consider an ATM machine.
You can perform operations such as:
You do not need to know the internal banking operations performed by the ATM.
Python provides the abc module for creating abstract base classes.
The two commonly used components are:
ABCabstractmethodfrom abc import ABC, abstractmethod
A class can inherit from ABC and define abstract methods using @abstractmethod.
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.
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()
Dog barks
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.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.
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.
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()
Car starts with a key Bike starts with a button
Both classes follow the same interface, but each class provides its own implementation.
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()
Python raises a TypeError because Animal still has an abstract method.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
pass
dog = Dog()
This also raises a TypeError because Dog has not implemented the abstract method sound().
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.
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())
50 30
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()
Animal eats food Dog barks
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)
Paid 1000 using cash Paid 2000 using card
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()
Calculating full-time salary Calculating part-time salary
| 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 | 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. |
Abstract classes are useful when several classes should follow the same interface but need different implementations.
Common examples include:
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")
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.
ABC as the base class for an abstract base class.@abstractmethod to declare an abstract method.abc module for abstraction.ABC is used to create abstract base classes.@abstractmethod is used to define abstract methods.Question: Which module is commonly used to implement abstraction in Python?