Junior — Middle
Can interfaces be used in Python and how is it implemented?
sobes.tech AI
Answer from AI
Python does not have a built-in keyword for interfaces like Java or C#. However, interfaces can be implemented using abstract base classes (ABC) from the abc module. They allow defining a set of methods that must be implemented in subclasses.
Example:
from abc import ABC, abstractmethod
class MyInterface(ABC):
@abstractmethod
def do_something(self):
pass
class Implementation(MyInterface):
def do_something(self):
print("Method implementation")
obj = Implementation()
obj.do_something() # Outputs: Method implementation
Thus, by using abc.ABC and the @abstractmethod decorator, you can create interface-like structures, ensuring that subclasses implement the required methods.