'Python - How to allow ABC subclasses to have custom additional parameters in __init__?

Consider the following:

from abc import ABC, abstractmethod

class ClassBase(ABC):
    @abstractmethod
    def __init__(self, name: str, value: int):
        pass

class Child1(ClassBase):
    def __init__(self, name: str, value: int, some_other_property: str):
        self.name = name
        self.value = value
        self.something = some_other_property

class Child2(ClassBase):
    def __init__(self, name: str, value: int, another_value: int):
        self.name = name
        self.value = value
        self.another = another_value

I want all classes that extend ClassBase ABC to include name and value parameters in their __init__ signature, and allow them to include some of their own parameters.

Is there a proper way to achieve this? I noticed that PyCharm IDE doesn't complain if the __init__ method of children classes doesn't match the ABC's, but it does for other abstract methods



Solution 1:[1]

Python doesn't complain about the signature. It only checks to see the child classes implement those abstractmethods. As long as your child classes implement all of the abstractmethods, then their instances are qualified to be a ClassBase object.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 S.B