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):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:
__init__
-signature in the abstract base class for documentation purposes.Finally, it is possible to have abstract classmethods, so this approach works as well:
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:
- Full documentation of the interface in the abstract base class.
- Concrete implementations usable as callables.
- 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!