Abstraction in Python

Abstraction in Python is a fundamental concept in object-oriented programming (OOP) that focuses on hiding the complex implementation details of a system and exposing only the necessary parts to the user. It allows developers to define abstract classes and methods, which can be implemented by derived classes, providing a way to create a clear and simplified interface for users while ensuring that the underlying complexity is encapsulated.

Characteristics of Abstraction

Example of Abstraction

This example demonstrates how to use abstraction in Python by defining an abstract class and implementing its methods in derived classes.

Code Example

from abc import ABC, abstractmethod
        
        # Abstract class
        class Animal(ABC):
            @abstractmethod
            def sound(self):
                pass
        
        # Derived class - Dog
        class Dog(Animal):
            def sound(self):
                return "Bark"
        
        # Derived class - Cat
        class Cat(Animal):
            def sound(self):
                return "Meow"
        
        # Function to demonstrate abstraction
        def animal_sound(animal):
            print(animal.sound())
        
        # Creating instances
        dog = Dog()
        cat = Cat()
        
        # Demonstrating abstraction
        animal_sound(dog)  # Output: Bark
        animal_sound(cat)  # Output: Meow

Output

Bark
Meow

Conclusion

Abstraction is a key principle in Python that enables developers to create simplified interfaces while hiding the complexities of the underlying implementation. By utilizing abstract classes and methods, programmers can ensure a consistent structure across different implementations, leading to better-organized and more maintainable code.