I have a class in Python that I want to instantiate with kwargs: e.g.
a = ClassA(happy=True)
I want to override this class with ClassB and set happy to True, I assumed this definition would work:
class ClassB(ClassA(happy=True))
However I get:
TypeError: 'ClassA' object is not callable
The workaround I have currently is to define ClassB as:
class ClassB(ClassA)
But then every time I instantiate ClassB, I have to do this:
b = ClassB(happy=True)
Anyone know how to do this?
This is how to do it:
class ClassB(ClassA):
def __init__(self, happy=True):
super().__init__(happy=happy)
When defining base classes of a class, that is all you do - define the base classes (here: (ClassA)
).
What happens when you want create an instance of your class (e.g. ClassB()
) is that its constructor (__init__
) is called.
The base class apparently has a constructor which takes False
as the default value, so you override the constructor and change its default argument value.
Then, call the base constructor with whatever the value is (super().__init__(happy=happy)
).