- Home
- Course Detail
regularpython@gmail.com
You are now watching:
Python Basics in English / of Abstract Class
Python Abstract Class – Concept, Rules & Real-Time Examples
1. What is an Abstract Class?
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.
➤
It contains one or more abstract methods (methods without implementation).
➤
Child classes must implement these abstract methods.
Real-Time Meaning
Think of an abstract class like a job rulebook. It defines what every employee must do, but the rulebook itself is not an employee.
2. Why Do We Use Abstract Classes?
✔
To enforce a common structure in all child classes.
✔
To achieve partial abstraction (hide some logic).
✔
To ensure child classes implement mandatory behaviours.
3. How to Create an Abstract Class in Python?
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.
4. Real-Time Example – Different Payment Methods
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)
5. Rules of Abstract Classes
1.
You cannot create objects of an abstract class.
2.
Child classes must implement all abstract methods.
3.
Abstract classes can have normal methods as well.
4.
They are used to create common structure / blueprint.
6. Abstract Class with Normal Methods
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()
7. Summary
•
Abstract class = blueprint + rules.
•
Must have abstract methods.
•
Child classes must override them.
•
Used to enforce structure in real-time projects.