What is abstraction in python?

What is abstraction in python?

What is Abstraction in Python?

Abstraction is one of the four key principles of Object-Oriented Programming (OOP), alongside encapsulation, inheritance, and polymorphism. It involves hiding the implementation details of a process and exposing only the essential features or functionality. Abstraction simplifies the complexity of a system by focusing on what an object does rather than how it does it.



Key Features of Abstraction

  1. Hides Complexity: Only the necessary details are exposed to the user.
  2. Focus on Functionality: The user does not need to know the internal working of methods or classes.
  3. Enhances Security: Prevents direct access to sensitive data and implementation.

In Python, abstraction can be achieved through:

  • Abstract classes
  • Abstract methods

Abstract Classes in Python

An abstract class serves as a blueprint for other classes. It cannot be instantiated and is defined using the ABC (Abstract Base Class) module from the abc library. Abstract classes can have both abstract methods (methods with no implementation) and concrete methods (methods with implementation).


Example 1: Abstract Class and Abstract Methods


from abc import ABC, abstractmethod

class Vehicle(ABC):
    @abstractmethod
    def start_engine(self):
        pass

    @abstractmethod
    def stop_engine(self):
        pass

class Car(Vehicle):
    def start_engine(self):
        print("Car engine started!")

    def stop_engine(self):
        print("Car engine stopped!")

class Bike(Vehicle):
    def start_engine(self):
        print("Bike engine started!")

    def stop_engine(self):
        print("Bike engine stopped!")

# Example usage
my_car = Car()
my_car.start_engine()  # Output: Car engine started!
my_car.stop_engine()   # Output: Car engine stopped!

my_bike = Bike()
my_bike.start_engine() # Output: Bike engine started!
my_bike.stop_engine()  # Output: Bike engine stopped!

In this example:

  • The Vehicle class is abstract, containing two abstract methods (start_engine and stop_engine).
  • The Car and Bike classes inherit from Vehicle and provide specific implementations for the abstract methods.

Example 2: Abstract Class with Concrete Methods

An abstract class can also include concrete methods to provide default behavior.


from abc import ABC, abstractmethod

class Appliance(ABC):
    def power_on(self):
        print("Appliance is now powered on.")

    @abstractmethod
    def function(self):
        pass

class WashingMachine(Appliance):
    def function(self):
        print("Washing clothes.")

class Refrigerator(Appliance):
    def function(self):
        print("Cooling food items.")

# Example usage
wm = WashingMachine()
wm.power_on()  # Output: Appliance is now powered on.
wm.function()  # Output: Washing clothes.

fridge = Refrigerator()
fridge.power_on()  # Output: Appliance is now powered on.
fridge.function()   # Output: Cooling food items.

Here:

  • The Appliance class provides a default power_on method.
  • Subclasses WashingMachine and Refrigerator implement the function method as per their requirements.

Example 3: Practical Use Case of Abstraction

Abstraction is commonly used when developing APIs or libraries where you expose only the essential methods while hiding complex details.


from abc import ABC, abstractmethod

class PaymentProcessor(ABC):
    @abstractmethod
    def process_payment(self, amount):
        pass

class PayPal(PaymentProcessor):
    def process_payment(self, amount):
        print(f"Processing payment of ${amount} through PayPal.")

class Stripe(PaymentProcessor):
    def process_payment(self, amount):
        print(f"Processing payment of ${amount} through Stripe.")

# Example usage
payment_method = PayPal()
payment_method.process_payment(100)  # Output: Processing payment of $100 through PayPal.

payment_method = Stripe()
payment_method.process_payment(200)  # Output: Processing payment of $200 through Stripe.

In this example:

  • PaymentProcessor defines a common interface for processing payments.
  • The specific payment gateways (PayPal and Stripe) implement their own methods while adhering to the interface.

Advantages of Abstraction

  1. Simplifies Maintenance: By hiding complex logic, it makes the system easier to maintain.
  2. Promotes Reusability: Common methods can be defined in an abstract class and reused in derived classes.
  3. Improves Security: Sensitive operations are hidden from the end user.

When to Use Abstraction?

  1. When you want to create a blueprint for other classes.
  2. When defining a standard for a group of classes.
  3. When working with APIs or frameworks where only essential methods need to be exposed.

Conclusion

Abstraction in Python allows developers to design systems that are easier to understand, maintain, and scale. By focusing on what an object does rather than how it does it, abstraction ensures clean and efficient code. Use abstract classes and methods to enforce implementation standards and promote consistency across your Python applications.

For more Python tips and tutorials, follow @PythonBeeTelugu on YouTube!

Comments