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
In Python, you can emulate Java-like interfaces using abstract base classes (abc module). Here is a brief summary on how you can achieve this: ```python from abc import ABC, abstractmethod class MyInterface(ABC): @abstractmethod def method_to_implement(self): pass ``` Here, we are declaring an abstract method `method_to_implement()`. An abstract method is a method declared in an abstract class but doesn't contain any implementation. Subclasses of this abstract class are generally expected to provide an implementation for this method. Now, any class that subclasses `MyInterface` has to implement `method_to_implement()`. If it doesn't, Python will raise a `TypeError` when you try to instantiate it. ```python class MyClass(MyInterface): def method_to_implement(self): return "Implemented method" ``` But remember, Python's philosophy is "we are all consenting adults here" which means the language trusts its users not to mess things up. The concept of interfaces is contrary to Python's dynamic typing system, but if you feel a necessity to strictly enforce interface patterns, this is how you can approach it.
Answered on August 15, 2023.
Add Comment

Your Answer

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