w3resource

What is abstraction in OOP (Python)?

Abstraction in OOP: Simplifying complexity with Python

In Object-Oriented Programming (OOP), abstraction simplifies complex reality by modeling classes based on the essential properties and behaviors an object should possess. It involves hiding complex implementation details while exposing only the necessary and relevant features.

A simplified definition of abstraction is focusing on what an object does rather than how it does it. It provides a high-level view of an object's functionality, making it easier to understand and use without getting bogged down in internal details.

Abstraction is achieved through the use of abstract classes and interfaces. An abstract class defines a blueprint for other classes to inherit from, while an interface defines a contract that classes must adhere to. Abstract constructs define common methods and properties that subclasses must implement.

For example, consider a car. It is not necessary to know how the engine works internally to drive it. It is only necessary to understand its interface, such as the accelerator pedal, brake pedal, and steering wheel. By abstracting away the car's internal mechanisms, you can interact with it more easily.

Abstraction can be achieved in Python using abstract base classes (ABCs) provided by the "abc" module. These classes allow you to define abstract methods that subclasses must implement.

Example:

Code:

from abc import ABC, abstractmethod

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

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14159 * self.radius ** 2

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

    def area(self):
        return self.length * self.width
circle = Circle(6)
rectangle = Rectangle(5,7)
print(circle.area())  # Output: 113.09724
print(rectangle.area())  # Output: 35

In the example above, "Shape" is an abstract class that defines an abstract method 'area()'. The concrete subclasses 'Circle' and 'Rectangle' inherit from "Shape" and implement the 'area()' method. The details of how the area is calculated are abstracted away, allowing us to interact with shapes using a higher-level interface.



Follow us on Facebook and Twitter for latest update.