Sobes.tech
Junior — Middle

What is the purpose of interfaces in programming?

sobes.tech AI

Answer from AI

An interface in programming is used to define a contract that a class must implement. It describes a set of methods (without implementation) that the class is obliged to implement.

In Python, interfaces are implemented through abstract base classes (ABC) from the abc module or through protocols (PEP 544).

Why are interfaces needed:

  • Ensuring standardization: different classes can implement the same interface, allowing them to be used interchangeably.
  • Supporting polymorphism: code can work with objects through the interface without knowing the specific implementation.
  • Improving architecture and code readability: clearly defines which methods must be implemented.

Example of an interface in Python using ABC:

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        print("Woof!")

class Cat(Animal):
    def make_sound(self):
        print("Meow!")

# Usage
animals = [Dog(), Cat()]
for animal in animals:
    animal.make_sound()

Thus, the interface defines a mandatory set of methods, ensuring consistency and flexibility of the code.