Python Abstraction

What is Abstraction?

Abstraction is one of the four core principles of Object-Oriented Programming (OOP), along with inheritance, encapsulation, and polymorphism.

Definition:

Abstraction means hiding the internal implementation and showing only the essential features of an object.

In Python, abstraction is typically implemented using abstract classes and abstract methods with the help of the abc module (abc stands for Abstract Base Classes).

Why Use Abstraction?

  • To simplify complexity.
  • To enforce a common interface across different classes.
  • To define blueprints for other classes.

Implementing Abstraction with abc Module

➤ Step-by-Step:

  1. Import ABC and abstractmethod from abc module.
  2. Create a class that inherits from ABC.
  3. Use @abstractmethod to define methods that must be implemented in subclasses.

Example: Abstract Class in Python

from abc import ABC, abstractmethod
class Vehicle(ABC):
   @abstractmethod
   def start_engine(self):
       pass
class Car(Vehicle):
   def start_engine(self):
       print("Car engine started.")
class Bike(Vehicle):
   def start_engine(self):
       print("Bike engine started.")

Usage:

c = Car()
c.start_engine()
b = Bike()
b.start_engine()

Output:

Car engine started.
Bike engine started.

Attempt to Instantiate Abstract Class

v = Vehicle()

Output (Error):

TypeError: Can't instantiate abstract class Vehicle with abstract methods start_engine

Explanation:

You cannot create an object of an abstract class directly. Only its subclasses that implement all abstract methods can be instantiated.

Example: Abstract Class with 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)
r = Rectangle(4, 5)
print("Area:", r.area())
print("Perimeter:", r.perimeter())

Output:

Area: 20
Perimeter: 18

Key Takeaways

FeatureDescription
Abstract ClassClass that cannot be instantiated
Abstract MethodMethod that must be implemented in a subclass
@abstractmethodDecorator to declare an abstract method
ABCBase class for all abstract classes
BenefitForces subclass to follow a structure (contract)