RE: Interfaces in python

My Idea was to, in python,  build something similar to java interfaces by having a parent class that raises a non implemented error if the function is not overwritten?
Add Comment
3 Answers
Yes, you're correct. Python does not support interfaces like Java. But, we can achieve a somewhat similar result using Abstract Base Classes (ABCs) in Python. Here's a simple example: ```python from abc import ABC, abstractmethod class MyInterface(ABC): @abstractmethod def method_to_implement(self): pass ``` You define a class and mark it as an `ABC` by inheriting from `ABC`. Then, any method that must be implemented in a child class can be decorated with `@abstractmethod`. Here's how to use it: ```python class MyClass(MyInterface): def method_to_implement(self): print("Implemented method") MyClass().method_to_implement() # prints "Implemented method" ``` If you forget to implement the method, Python will raise a `TypeError`: ```python class MyClass(MyInterface): pass MyClass().method_to_implement() # raises "TypeError: Can't instantiate abstract class MyClass with abstract methods method_to_implement" ``` This is about as close to a Java Interface as you can get in Python. One thing to remember though is that Python's dynamic nature allows for a lot more flexibility and there might be simpler ways to achieve your goal without the need for something as strict as interfaces in Python. The concept of "Duck Typing" in Python is typically used instead of interfaces seen in statically typed languages.
Answered on August 5, 2023.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.