• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: How to create a class with an abstract `__init__` method?

Resolved: How to create a class with an abstract `__init__` method?

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I want to create an abstract base class in Python where part of the contract is how instances can be created. The different concrete implementations represent various algorithms that can be used interchangeably. Below is a simplified example (usual disclaimer – the real use-case is more complex):
The above works, but has the drawback that I can’t call super().__init__(...) in ConcreteAlgorithm.__init__, which might break certain inheritance scenarios, I think (correct me if I’m wrong here, but calling super is important for multiple inheritance, right?). (Strictly speaking __init__ can be called, but with the same signature as the subclass __init__, which doesn’t make sense).
Python classes are callables, so I could also express it like this:
This works and doesn’t have the drawback mentioned above, but I do like having the __init__-signature in the abstract base class for documentation purposes.
Finally, it is possible to have abstract classmethods, so this approach works as well:
This works, but I lose the nice property of using algorithm like a callable (it’s just more flexible, in case someone actually wants to drop in a function, for example to decide which algorithm to use based on certain parameter values).
So, is there an approach that satisfies all three requirements:
  1. Full documentation of the interface in the abstract base class.
  2. Concrete implementations usable as callables.
  3. No unsafe behavior like not being able to call the base-class __init__.

Answer:

Strictly speaking __init__ can be called, but with the same signature as the subclass __init__, which doesn’t make sense.


No, it makes perfect sense.
You’re prescribing the signature because you require each child class to implement it exactly. That means you need to call it exactly like that as well. Each child class needs to call its super().__init__ exactly according to the abstract definition, passing all defined parameters along.

If you have better answer, please add a comment about this, thank you!

abstract-class python
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: TypeScript does not recognize properties when instantiating interface array

27/03/2023

Resolved: How to make statement case insensitive when uploading a dta file with specified columns?

27/03/2023

Resolved: Sort dataframe columns value by close it to another column

27/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.