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
While Python doesn't support interfaces like Java, you can mimic that behavior using abstract base classes (ABCs) and the `abc` module. Here is a brief example of how you might define a similar 'interface' in Python: ```python from abc import ABC, abstractmethod class MyInterface(ABC): @abstractmethod def method_to_implement(self): pass ``` And an implementation of this 'interface': ```python class MyClass(MyInterface): def method_to_implement(self): return "I've implemented this!" ``` Here, `MyInterface` works similarly to an interface. Any class that is subclassed from `MyInterface` is required to provide an implementation for `method_to_implement()`. If it doesn't, Python will raise a `TypeError`. This mechanism of ABCs and the `abc` module in Python provide a way of ensuring certain methods are present in child classes, and thereby offers a manner of interface enforcement. Remember that Python’s philosophy is "we're all consenting adults here". It trusts that we'll adhere to the methods outlined in the parent class where it's necessary, instead of enforcing it via the language syntax itself like Java. ABCs are there if you need some enforceability, but don't always perfectly align with Python's core design principles.
Answered on August 5, 2023.
Add Comment

Your Answer

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