3

I want implementations of my abstract class to accept an integer. For this, I can

from abc import ABC, abstractmethod

class Base(ABC):
    @abstractmethod
    def __init__(self, i: int):
        pass

and then implementations will be like

class Sub(Base):
    def __init__(self, i: int):
        ...

but since I can change the signature of __init__ without violating LSP, I can also

class Sub2(Sub):
    def __init__(self, s: str):
        ...

and the signature of Base.__init__ is lost, and isn't enforced by the ABC. That is, only direct descendants of Base must have the same __init__ signature. If subclasses were strictly required to call superclass's __init__ methods, this wouldn't be a problem, because Sub2 would need to provide an int to Sub, but afaict that's optional.

Given this, does making __init__ abstract make sense? Or, more broadly, should subclasses ever be expected to have a given type signature?

joel
  • 6,359
  • 2
  • 30
  • 55
  • Of course type hints are used by type checkers, but it is also a documentation for human. If you recommend subclasses type signature for `__init__`, putting it into abstract `__init__` will have good meaning of recommendation. – youknowone May 08 '19 at 12:25
  • Given the nature of abstract methods, making `__init__` abstract seems like it would just be a very strong hint that the child do something specific in its `__init__` method, rather than simply assuming that the upstream `__init__` is sufficient. Being abstract doesn't say anything about the required signature, only that something by that *name* is defined. – chepner May 08 '19 at 12:52

0 Answers0