I want to add keyword arguments to a derived class, but can't figure out how to go about it. Trying the obvious
class ClassA(some.package.Class):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class ClassB(ClassA):
def __init__(self, *args, a='A', b='B', c='C', **kwargs):
super().__init__(*args, **kwargs)
self.a=a
self.b=b
self.c=c
fails because I can't list parameters like that for ClassB
's __init__
. And
class ClassB(ClassA):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.a=a
self.b=b
self.c=c
of course doesn't work because the new keywords aren't specified.
How do I add keyword arguments to the __init__
for a derived class?
Embrace keyword arguments in Python Consider using the * operator to require those arguments be specified as keyword arguments. And remember that you can accept arbitrary keyword arguments to the functions you define and pass arbitrary keyword arguments to the functions you call by using the ** operator.
Creating the constructor in python It accepts the self-keyword as a first argument which allows accessing the attributes or method of the class. We can pass any number of arguments at the time of creating the class object, depending upon the __init__() definition. It is mostly used to initialize the class attributes.
Python allows functions to be called using keyword arguments. When we call functions in this way, the order (position) of the arguments can be changed.
Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter names. A keyword argument is preceded by a parameter and the assignment operator, = . Keyword arguments can be likened to dictionaries in that they map a value to a keyword.
Try doing it like this:
class ClassA:
def __init__(self, *args, **kwargs):
pass
class ClassB(ClassA):
def __init__(self, *args, **kwargs):
self.a = kwargs.pop('a', 'A')
self.b = kwargs.pop('b', 'B')
self.c = kwargs.pop('c', 'C')
super().__init__(*args, **kwargs)
Effectively you add the keyword arguments a
, b
and c
to ClassB
, while passing on other keyword arguments to ClassA
.
All you need do is rearrange the arguments.
def __init__(self, a='A', b='B', c='C', *args, **kwargs):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With