0

Suppose I have a python class with arguments in the __init__ method with types specified.

class A:
    def __init__(self, arg_1:int, ..., arg_n:int):
        pass

Suppose I inherit from it as such:

class B(A):
    def __init__(self, arg_2:int, ..., arg_n:int):
        super().__init__(arg1="str", arg_2, ..., arg_n)

The problem here is that I have to write the the whole argument list including the types. If I decide to change the type of one argument to some other type, I have to do so for all subclasses. How can we avoid this?

One possible solution could be the one below. However, the constructor here does not show the list of arguments as they are defined in Class A.

class B(A):
    def __init__(self, **kwargs):
        super().__init__(arg1="str", **kwargs)

Is it maybe possible to group the common arguments in one class and share that in all classes?

2
  • 1
    Why not use a dataclass to create a Params object containing the arguments and instantiate both A and B with an object of class Params? Commented Oct 25, 2024 at 11:26
  • The possible solution is indeed what is recommended by rhettinger.wordpress.com/2011/05/26/super-considered-super. Ultimately, you don't know that super().__init__ refers to A.__init__, as it depends entirely on the runtime type of self. As such, it's not really a problem that it doesn't list A's parameters, because there might be more than just A's parameters that need to be filled. Commented Oct 31, 2024 at 14:24

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.