An Abstract Class is a class that cannot be instantiated directly. It is used to define a common interface or contract for all its child classes.
It contains one or more abstract methods, which must be implemented by any subclass.
Python provides the abc
module to define abstract classes using ABC
(Abstract Base Class) and @abstractmethod
.
Term | Description |
---|---|
ABC |
Abstract Base Class imported from abc module |
@abstractmethod |
Decorator to define methods that must be implemented |
Concrete Class | A subclass that provides implementation of abstract methods |
Interface | Set of methods a class must implement |
Polymorphism | Allows using different classes interchangeably if they implement the same abstract interface |
Imagine you're building a system that supports multiple payment gateways like Razorpay, Stripe, and PayPal. You want to enforce that every payment gateway class must implement the methods: connect()
and process_payment()
.
from abc import ABC, abstractmethod
# Abstract base class
class PaymentGateway(ABC):
@abstractmethod
def connect(self):
pass
@abstractmethod
def process_payment(self, amount):
pass
class RazorpayGateway(PaymentGateway):
def connect(self):
print("Connecting to Razorpay API...")
def process_payment(self, amount):
print(f"Processing ₹{amount} via Razorpay")
class StripeGateway(PaymentGateway):
def connect(self):
print("Connecting to Stripe API...")
def process_payment(self, amount):
print(f"Processing ${amount} via Stripe")
class PayPalGateway(PaymentGateway):
def connect(self):
print("Connecting to PayPal API...")
def process_payment(self, amount):
print(f"Processing ${amount} via PayPal")
# Reusable function
def make_payment(gateway: PaymentGateway, amount):
gateway.connect()
gateway.process_payment(amount)
# Use Stripe
make_payment(StripeGateway(), 500)