Python Guide Sidebar

Python – Abstraction

What is Abstraction in Python?

Abstraction is one of the fundamental principles of Object-Oriented Programming (OOP). It allows developers to hide unnecessary implementation details and expose only the essential features of an object. This simplifies code management, enhances security, and promotes modularity.

In Python, abstraction is achieved using abstract classes and abstract methods, which are defined in the abc (Abstract Base Classes) module.

Why Use Abstraction?
  1. Encapsulation of Complexity: Hides complex logic and provides a simple interface.
  2. Code Reusability: Promotes code reuse by defining common functionalities in abstract classes.
  3. Enhanced Security: Prevents direct modification of sensitive data.
  4. Flexibility in Design: Allows developers to define a blueprint without implementing full functionality.
How to Implement Abstraction in Python?

Python provides the abc module to implement abstraction using abstract classes and methods.

1. Abstract Classes

An abstract class cannot be instantiated and serves as a blueprint for other classes.

2. Abstract Methods

An abstract method is a method that is declared in an abstract class but does not include an implementation. Consequently, it must be overridden and implemented by subclasses.

Example of Abstraction in Python:

from abc import ABC, abstractmethod

# Defining an abstract class
class Animal(ABC):
    
    @abstractmethod
    def make_sound(self):
        pass  # Abstract method with no implementation

# Subclass implementing the abstract method
class Dog(Animal):
    def make_sound(self):
        return "Woof!"

class Cat(Animal):
    def make_sound(self):
        return "Meow!"

# Creating instances of subclasses
dog = Dog()
cat = Cat()
print(dog.make_sound()) 
print(cat.make_sound())  



In the above example, the Animal class is an abstract class that contains an abstract method, make_sound(). As a result, the Dog and Cat classes inherit from Animal and provide their own implementations of make_sound().

Real-World Use Case of Abstraction

Consider a payment system where multiple payment methods (credit card, PayPal, UPI) exist. Instead of implementing individual logic for each payment method, an abstract class can define a common interface.

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")

# Using the abstraction
payment = CreditCardPayment()
payment.pay(1000)

This approach ensures that any new payment method can be easily added without modifying the existing code structure.

Conclusion

Abstraction in Python helps developers create clean, modular, and maintainable code by clearly separating an interface from its implementation. Moreover, it plays a crucial role in software architecture by enhancing scalability and security.

Additional Topics:


Interview Questions:

1. What is abstraction in Python, and why is it important? (Infosys)

Answer:
Abstraction in Python is an object-oriented programming concept that hides implementation details and only exposes essential functionalities to the user. It helps in reducing complexity and improving code reusability by focusing on “what” a function or class does rather than “how” it does it.
For example, when using a car, we only need to know how to start and drive it, without understanding its internal mechanisms. Similarly, abstraction in Python allows users to interact with an interface without worrying about underlying implementation details.


2. How can abstraction be implemented in Python? (TCS)

Answer:
In Python, developers use abstract classes and abstract methods with the ABC module (Abstract Base Class) to implement abstraction. Consequently, an abstract class defines a blueprint for other classes, and developers cannot instantiate it directly.


3. What is the difference between abstraction and encapsulation in Python? (Amazon)

Answer:

  • Abstraction simplifies complex systems by hiding implementation details while exposing only essential functionalities. Developers achieve this through abstract classes and interfaces, ensuring a clean and modular design.
  • Encapsulation, therefore, restricts direct access to an object’s data and methods to prevent unintended modifications. Consequently, developers implement it using private (__variable) and protected (_variable) access specifiers.

Example:

  • Encapsulation: It ensures better data protection by keeping attributes private so that users cannot modify them directly.
  • Abstraction: Developers use abstract methods in order to enable user interaction while effectively hiding the underlying logic.

Abstraction Quizzes