Sobes.tech
Junior — Middle

What are the advantages and disadvantages of using interfaces implemented through abstract classes in Python?

sobes.tech AI

Answer from AI

In Python, interfaces are often implemented through abstract classes using the abc module.

Advantages:

  • Allow defining mandatory methods that must be implemented in subclasses.
  • Provide a unified contract for different implementations.
  • Partial logic can be implemented in an abstract class, which will be used by inheritors.

Disadvantages:

  • Python is a dynamic language, and strict interfaces are not always necessary; sometimes duck typing suffices.
  • Using abstract classes can complicate the code structure.
  • Multiple inheritance can lead to complexities with method resolution order (MRO).

Example:

from abc import ABC, abstractmethod

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

class Dog(Animal):
    def make_sound(self):
        return "Bark"

# dog = Animal()  # Error: cannot instantiate abstract class
dog = Dog()
print(dog.make_sound())  # Bark