What is an interface in the context of Python OOP, and how is it implemented?

What is an interface in the context of Python OOP, and how is it implemented?

a) An interface is a collection of abstract methods that can be implemented by multiple classes using inheritance or abstract base classes
b) An interface is a keyword used to define an abstract class in Python
c) An interface is a way to implement multiple inheritance in Python
d) Python does not support the concept of interfaces

Answer:

a) An interface is a collection of abstract methods that can be implemented by multiple classes using inheritance or abstract base classes

Explanation:

In Python, an interface is typically a collection of abstract methods defined in an abstract base class (ABC). Other classes can implement this interface by inheriting from the ABC and providing concrete implementations for the abstract methods. This allows multiple classes to share a common interface while implementing their specific behaviors.

from abc import ABC, abstractmethod

class Drawable(ABC):
    @abstractmethod
    def draw(self):
        pass

class Circle(Drawable):
    def draw(self):
        print("Drawing a circle")

class Square(Drawable):
    def draw(self):
        print("Drawing a square")

# Creating objects of Circle and Square
shapes = [Circle(), Square()]
for shape in shapes:
    shape.draw()  # Output: Drawing a circle
                  #         Drawing a square

In this example, Drawable is an abstract base class that defines the draw() method. The Circle and Square classes implement this interface by providing their versions of the draw() method.

Using interfaces (through ABCs) in Python helps create a consistent API across multiple classes, promoting code reusability and maintainability.

Leave a Comment

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

Scroll to Top