An abstract class is a class that cannot be instantiated (you cannot create objects directly). It is used to provide a template or blueprint for other classes.
Think of an abstract class like a job rulebook. It defines what every employee must do, but the rulebook itself is not an employee.
We use the abc module:
from abc import ABC, abstractmethod
class Payment(ABC): # abstract class
@abstractmethod
def make_payment(self):
pass # no implementation
Here, Payment is an abstract class, and make_payment() is an abstract method.
In every company application, there will be multiple payment methods such as Credit Card, Debit Card, UPI, etc. Abstract class ensures that every payment class must have a make_payment() method.
from abc import ABC, abstractmethod
class Payment(ABC):
@abstractmethod
def make_payment(self, amount):
pass
class CreditCardPayment(Payment):
def make_payment(self, amount):
print(f"Paid {amount} using Credit Card")
class DebitCardPayment(Payment):
def make_payment(self, amount):
print(f"Paid {amount} using Debit Card")
# Usage
cc = CreditCardPayment()
cc.make_payment(500)
from abc import ABC, abstractmethod
class Vehicle(ABC):
def engine(self):
print("Engine started")
@abstractmethod
def wheels(self):
pass
class Bike(Vehicle):
def wheels(self):
print("Bike has 2 wheels")
bk = Bike()
bk.engine()
bk.wheels()