What is Abstraction?

11
0

Abstraction is a principle of object-oriented programming that refers to the ability to focus on the essential features of an object and ignore the non-essential details. It is one of the four fundamental OOP concepts, along with encapsulation, inheritance, and polymorphism.

Abstraction can be achieved in Python through the use of abstract classes and methods. An abstract class is a class that contains one or more abstract methods, which are methods that have a declaration, but no implementation. This means that you cannot create an instance of an abstract class, and you must subclass the abstract class and provide an implementation for the abstract methods in the subclass.

Here is an example of an abstract class in Python:

from abc import ABC, abstractmethod

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

In this example, the Shape class is an abstract class that defines two abstract methods, area and perimeter. These methods have a declaration, but no implementation, so they cannot be called directly. Instead, they must be implemented in a subclass of the Shape class.

Here is an example of how you might subclass the Shape class to create a concrete class:

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height
        
    def area(self):
        return self.width * self.height
    
    def perimeter(self):
        return 2 * (self.width + self.height)

In this example, the Rectangle class is a concrete class that subclasses the Shape class and provides an implementation for the area and perimeter methods. This allows you to create instances of the Rectangle class and call the area and perimeter methods on those instances.

Using abstraction, you can define a common interface for a group of related classes, and allow the implementation details to vary between the classes. This can help to reduce complexity and increase the maintainability of your code.

Leave a Reply

Your email address will not be published. Required fields are marked *