SimpleTuts.com

Python Abstraction

Abstraction in Python

Abstraction is a fundamental concept in object-oriented programming (OOP). It involves hiding the complex implementation details and showing only the essential features of the object.

Example: Abstract Base Class (ABC)

Python provides a module called abc (Abstract Base Classes) to define abstract base classes. Let's create an abstract class Shape with an abstract method area():


import abc

class Shape(abc.ABC):
    
    @abc.abstractmethod
    def area(self):
        pass

class Circle(Shape):
    
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        return 3.14 * self.radius * self.radius

class Rectangle(Shape):
    
    def __init__(self, length, width):
        self.length = length
        self.width = width
    
    def area(self):
        return self.length * self.width

# Usage
circle = Circle(5)
print("Area of circle:", circle.area())

rectangle = Rectangle(3, 4)
print("Area of rectangle:", rectangle.area())
            

In this example, Shape is an abstract base class with an abstract method area(). The Circle and Rectangle classes inherit from Shape and provide concrete implementations of the area() method.

Conclusion

Abstraction allows us to create hierarchies of classes with shared characteristics while hiding implementation details. Python's abc module provides a convenient way to define abstract base classes and enforce structure in your programs.