Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add keyword arguments to a derived class's constructor in Python?

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?

like image 751
orome Avatar asked Dec 14 '14 17:12

orome


People also ask

How do I set keyword arguments in Python?

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.

How do you pass a parameter to a constructor in Python?

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.

Does Python support keyword arguments?

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.

What are keyword arguments how they are used in Python?

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.


2 Answers

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.

like image 82
aknuds1 Avatar answered Oct 10 '22 19:10

aknuds1


All you need do is rearrange the arguments.

def __init__(self, a='A', b='B', c='C', *args, **kwargs):
like image 36
Aran-Fey Avatar answered Oct 10 '22 19:10

Aran-Fey