Abstraction in Python
Abstraction is one of the core concepts of Object-Oriented Programming (OOP). In simple words, abstraction means hiding internal implementation details and showing only the necessary features of an object to the user.
Python achieves abstraction using abstract classes and
abstract methods with the help of the built-in abc module.
🔹 Real-Life Example of Abstraction
When you drive a car, you only use the steering, accelerator, brake, and gear. You don't need to know how the engine works internally. This is abstraction — only essential features are visible, internal complexity is hidden.
🔹 Why Abstraction is Important?
- Improves code readability
- Reduces complexity
- Enhances security by hiding internal logic
- Makes code scalable and maintainable
- Supports loose coupling
🔹 Abstract Class in Python
An abstract class is a class that cannot be instantiated directly. It is used as a blueprint for other classes.
Python provides the abc module to create abstract classes.
Syntax
from abc import ABC, abstractmethod
class ClassName(ABC):
@abstractmethod
def method_name(self):
pass
🔹 Example of Abstraction in Python
from abc import ABC, abstractmethod
# Abstract class
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
# Child class
class Car(Vehicle):
def start(self):
print("Car engine started")
def stop(self):
print("Car engine stopped")
# Child class
class Bike(Vehicle):
def start(self):
print("Bike engine started")
def stop(self):
print("Bike engine stopped")
# Object creation
car = Car()
car.start()
car.stop()
bike = Bike()
bike.start()
bike.stop()
Output
Car engine started Car engine stopped Bike engine started Bike engine stopped
🔹 Key Rules of Abstraction in Python
- Abstract classes must inherit from
ABC - Abstract methods must use
@abstractmethod - Child classes must implement all abstract methods
- Objects of abstract classes cannot be created
🔹 Abstraction vs Encapsulation
| Abstraction | Encapsulation |
|---|---|
| Hides implementation logic | Hides data using access control |
| Focuses on "what to do" | Focuses on "how to protect data" |
| Achieved using abstract classes | Achieved using access modifiers & methods |
🔹 Interview Questions
- What is abstraction in Python?
- What is the abc module?
- Difference between abstract class and normal class?
- Can we create object of abstract class?
- Difference between abstraction and encapsulation?
🔹 Conclusion
Abstraction helps in building clean, secure, and scalable software systems. It allows developers to focus on what an object does rather than how it does it. Using abstraction properly makes Python applications more professional and maintainable.
No comments:
Post a Comment