Python Abstract Class

Description

🧱 Abstract Class in Python with Payment Gateway Template

📘 What is an Abstract Class?

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.

🔑 Key Terms

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

💳 Real-Time Scenario: Payment Gateway Template

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().

✅ Abstract Class Template in Python

from abc import ABC, abstractmethod

# Abstract base class
class PaymentGateway(ABC):
    @abstractmethod
    def connect(self):
        pass

    @abstractmethod
    def process_payment(self, amount):
        pass

💡 Razorpay Implementation

class RazorpayGateway(PaymentGateway):
    def connect(self):
        print("Connecting to Razorpay API...")

    def process_payment(self, amount):
        print(f"Processing ₹{amount} via Razorpay")

💡 Stripe Implementation

class StripeGateway(PaymentGateway):
    def connect(self):
        print("Connecting to Stripe API...")

    def process_payment(self, amount):
        print(f"Processing ${amount} via Stripe")

💡 PayPal Implementation

class PayPalGateway(PaymentGateway):
    def connect(self):
        print("Connecting to PayPal API...")

    def process_payment(self, amount):
        print(f"Processing ${amount} via PayPal")

🔁 Using Any Gateway

# Reusable function
def make_payment(gateway: PaymentGateway, amount):
    gateway.connect()
    gateway.process_payment(amount)

# Use Stripe
make_payment(StripeGateway(), 500)
Output:
Connecting to Stripe API...
Processing $500 via Stripe