Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract classes in Python, is it wrong to add methods with and without implementation

I know that Java abstract classes may contain a mix of methods declared with or without an implementation.

Can the same be said about python simulated abstract classes?

The examples that I have gathered so far online is with no implementation.I am trying to maintain good coding habits with Python and would like to know the pythonic way.


1 Answers

You should note that abstract methods/classes aren't a core language feature in Python as they are in Java, though this behaviour can be simulated using ABC (abstract base class) and the @abstractmethod decorator.

However, similarly to Java, this approach is fine. Your non-abstract method(s) will be inherited from your superclass as normal and your abstract methods will require an explicit subclass implementation only if declared as abstract using the @abstractmethod decorator. Otherwise, Python won't complain that an "abstract" method isn't implemented in a subclass. It's worth looking at the Abstract Base Class documentation which covers this.

Inherited non-abstract methods can also be overridden in subclasses if needed, providing a new implementation if some extra-specific logic is required further down in your inheritance hierarchy.

like image 57
psilocybin Avatar answered Oct 21 '25 16:10

psilocybin