↓ Skip to main content
Python

Python: Interface

·1 min

n Python, unlike some other programming languages, there is no explicit syntax for defining interfaces. However, you can create a similar concept by defining an abstract base class (ABC) that contains abstract methods. An abstract method is a method that is declared in a base class, but has no implementation. Subclasses of the abstract base class must implement these abstract methods.

Here’s an example:

from abc import ABC, abstractmethod

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

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side * self.side

square = Square(5)
print(square.area())  # 25

In the example above, the Shape class is defined as an abstract base class using the ABC class from the abc module.

The area method is defined as an abstract method using the @abstractmethod decorator. The Square class is a concrete implementation of the Shape interface, and implements the area method. When you create an instance of the Square class and call its area method, the implementation of the area method in the Square class is executed, and the result is returned.

The “@” symbol in Python is used to define decorators. Decorators are a way to modify the behavior of a function, class, or method by wrapping it in another function. — Help
Author
Samarthya
Engineer, learner, tinkerer. This is my trophy shelf of everyday work and leisure.

Related

Python: Class

·1 min
Learning to write Python code? A Python class is a blueprint for creating objects. It defines a set of attributes and methods that can be used to manipulate those attributes. Here’s an example of a simple Python class:

Python: Decorators

·1 min
Let’s learn about decorators @iamdecorator Decorators are used to modify or extend the behavior of functions and classes. They are useful for wrapping a function or class with additional functionality, such as logging, access control, performance measurement, or adding attributes. This can reduce code duplication, increase readability and maintainability.

Python: Inheritance

·2 mins
Inheritance is a mechanism in object-oriented programming (OOP) that allows you to create new classes that are derived from existing classes. The derived class inherits attributes and behaviors from the base class, and can also have additional attributes and behaviors of its own.