Is there a way to instantiate a child class that inherits all arguments from the parent class AND adds new arguments while:
- keeping the argument order intact;
- not requiring keyword arguments;
- changing with the parent class?
Or is this an unconventional/unpythonic thing to do?
The following minimal-working example should explain my question more clearly.
Thanks in advance!
class Parent:
'''
Sample Parent class.
Arguments
---------
arg1: int
Sample argument 1.
arg2: int
Sample argument 2.
arg3: int
Sample argument 3.
'''
def __init__(self, arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
class Child(Parent):
'''
Sample Child class.
Arguments
---------
arg1: int
Sample argument 1.
arg2: int
Sample argument 2.
arg3: int
Sample argument 3.
arg4: int
Sample argument 4.
'''
# THIS CHANGES THE ORDER OF THE ARGUMENTS (arg4 is first.)
def __init__(self, arg4, *args):
super().__init__(*args)
self.arg4 = arg4
# THIS MAKES arg4 A KEYWORD-ONLY ARGUMENT.
def __init__(self, *args, arg4):
super().__init__(*args)
self.arg4 = arg4
# THIS REQUIRES MANUAL CHANGES IF THE PARENT CHANGES.
def __init__(self, arg1, arg2, arg3, arg4):
super().__init__(arg1, arg2, arg3)
self.arg4 = arg4
CodePudding user response:
You could define the parent class to also use *args
def __init__(self, *args):
self.arg1 = args[0]
self.arg2 = args[1]
self.arg3 = args[2]
And then the child:
def __init__(self, *args):
super().__init__(*args)
self.arg4 = args[-1]
This will pass all args to the parent but it would use only the first 3. The child will use only the last element in args