🔍 What is Abstraction in Python?
Abstraction in Python is an Object-Oriented Programming (OOP) concept that hides complex implementation details and shows only the necessary features of an object.
It helps reduce code complexity and increases reusability and maintainability.
📌 Why Use Abstraction?
- Hide implementation logic from users.
- Reduce code duplication.
- Define common interfaces for different classes.
- Improve code modularity and security.
📘 How to Implement Abstraction in Python?
We use the abc
module to implement abstraction in Python. It allows us to create abstract base classes and abstract methods.
from abc import ABC, abstractmethod # Abstract class class Animal(ABC): @abstractmethod def make_sound(self): pass # Concrete class class Dog(Animal): def make_sound(self): return "Woof!" # Using the class d = Dog() print(d.make_sound())
🧠 Explanation
ABC
is the base class for defining abstract classes.@abstractmethod
decorator marks a method as abstract — subclasses must implement it.Dog
class inheritsAnimal
and provides an implementation formake_sound()
.
🚫 What If Abstract Methods Aren’t Implemented?
If a subclass doesn’t implement all abstract methods, you’ll get a TypeError.
class Cat(Animal): pass # This will raise an error c = Cat()
✅ Summary
- Abstraction hides internal details and exposes only what’s necessary.
- Implemented using
ABC
and@abstractmethod
. - Improves maintainability and enforces a consistent interface across related classes.
Mastering abstraction is a key step in writing clean and scalable object-oriented Python code.