*Abstraction & Interface *
1. What is Abstraction?
Abstraction means showing only essential details and hiding implementation.
Real life example:
- Driving a car → you only use steering, brake, accelerator
- Engine working → hidden
2. Why Abstraction is Needed?
✔ Reduces complexity
✔ Improves security
✔ Improves maintainability
✔ Forces standard structure
✔ Used in real projects
3. Abstract Class
An abstract class:
- Cannot create object
- Can contain abstract & normal methods
- Must be inherited
In Python we use
abcmodule.
4. Abstract Base Class (ABC)
from abc import ABC, abstractmethod
Abstract Method
A method without body; must be implemented by child class.
5. Example – Abstract Class
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
Cannot create object:
s = Shape() # Error
6. Implement Abstract Method in Child Class
class Square(Shape):
def init(self, side):
self.side = side
def area(self):
return self.side * self.side
sq = Square(5)
print(sq.area())
7. Multiple Abstract Methods
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
8. Interface in Python
Python does not have interface keyword like Java.
Abstract class with only abstract methods behaves like an interface.
9. Interface Example
class Bank(ABC):
@abstractmethod
def deposit(self, amt):
pass
@abstractmethod
def withdraw(self, amt):
pass
10. Implementing Interface
class SBI(Bank):
def deposit(self, amt):
print("Deposit:", amt)
def withdraw(self, amt):
print("Withdraw:", amt)
b = SBI()
b.deposit(5000)
b.withdraw(2000)
11. Abstract Class with Normal Methods
class Employee(ABC):
def office_rules(self):
print("Office time 9AM - 6PM")
@abstractmethod
def salary(self):
pass
12. Child Class Implementation
class Developer(Employee):
def salary(self):
print("Salary: 40,000")
d = Developer()
d.office_rules()
d.salary()
13. Important Rules of Abstraction
✔ Cannot create object of abstract class
✔ All abstract methods must be implemented
✔ Use ABC + abstractmethod
✔ Abstract class may have normal methods
✔ Used for code standards
14. Real-Time Example – Payment System
class Payment(ABC):
@abstractmethod
def pay(self, amount):
pass
class GooglePay(Payment):
def pay(self, amount):
print("Paid", amount, "using GooglePay")
class PhonePe(Payment):
def pay(self, amount):
print("Paid", amount, "using PhonePe")
15. Why Interface/Abstraction in Projects?
✔ Multiple developers work together
✔ Fixed method structure
✔ Easy to update or extend
✔ Safer code
✔ Cleaner architecture
Top comments (0)