w3resource

How do you achieve abstraction using abstract classes or interfaces in Python?

Achieving abstraction: Abstract classes and interfaces in Python

Abstraction in Python is achieved using abstract classes or interfaces provided by the "abc" module. Abstract classes define a common interface for their subclasses, while interfaces define a set of methods that must be implemented by classes that implement the interface. The use of abstract classes and interfaces allows you to create a high-level contract that all classes must adhere to.

In Python, there is no strict distinction between abstract classes and interfaces as seen in other programming languages like Java. Instead, in Python, abstract base classes (ABCs) are used to define a common interface that subclasses are expected to implement.

Here's an example using ABCs to achieve abstraction:

Code:

from abc import ABC, abstractmethod
# Define an abstract base class 'Shape'
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

# Define a class 'Circle' that inherits from 'Shape'
class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    def area(self):
        return 3.14159 * self.radius ** 2
# Define a class 'Rectangle' that inherits from 'Shape'
class Rectangle(Shape):
    def __init__(self, width, length):
        self.width = width
        self.length = length
    def area(self):
        return self.width * self.length
# Create instances of 'Circle' and 'Rectangle'
circle = Circle(4)
rectangle = Rectangle(5, 7)
# Calculate and print the area of the shapes
print(circle.area())  # Output: 50.26544
print(rectangle.area())  # Output: 35


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-interview/how-do-you-achieve-abstraction-using-abstract-classes-or-interfaces-in-python.php