Abstraction in Python
1. What is Abstraction?
Abstraction is an Object-Oriented Programming (OOP) concept that hides the implementation
details
of a process or system and exposes only the necessary functionality. It allows you to focus on what
an object does rather than how it does it.
In Python, abstraction can be achieved using:
- Abstract Base Classes (ABCs)
- Interfaces via the `abc` module
2. Key Features of Abstraction
- Hides Complexity: Users interact with high-level functionalities without worrying about the
implementation.
- Encourages Reusability: Abstract classes can be reused across projects.
- Improves Code Maintainability: Changes in implementation do not affect dependent objects.
- Focus on Design: Forces developers to think about the system's broader design.
3. Abstract Classes in Python
Abstract classes serve as blueprints for other classes and cannot be instantiated directly.
They are defined using the `abc` module.
4. Syntax for Abstract Classes
- Import the `abc` module.
- Inherit from `ABC` (Abstract Base Class).
- Define abstract methods using the `@abstractmethod` decorator.
Code Example:
------------------------------------------------------------
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
def sleep(self):
print("Sleeping...")
class Dog(Animal):
def sound(self):
print("Bark!")
class Cat(Animal):
def sound(self):
print("Meow!")
dog = Dog()
cat = Cat()
dog.sound() # Output: Bark!
cat.sound() # Output: Meow!
------------------------------------------------------------
5. Real-World Example: Payment System
------------------------------------------------------------
from abc import ABC, abstractmethod
class Payment(ABC):
@abstractmethod
def pay(self, amount):
pass
class CreditCardPayment(Payment):
def pay(self, amount):
print(f"Paid ${amount} using Credit Card")
class PayPalPayment(Payment):
def pay(self, amount):
print(f"Paid ${amount} using PayPal")
payment1 = CreditCardPayment()
payment1.pay(100) # Output: Paid $100 using Credit Card
------------------------------------------------------------
6. Key Points
- Abstract classes cannot be instantiated directly.
- Abstract methods must be implemented in subclasses.
- Abstract classes can have both abstract and concrete methods.
7. Interview Insights
- Common Questions:
* What is abstraction in Python?
* How are abstract classes implemented?
* Difference between abstraction and encapsulation?
- Coding Challenges:
* Design an abstract class for a vehicle management system.
* Implement a payment system using abstraction.