Search code examples
pythonconstructorkeyword-argument

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?


Solution

  • 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.