Setting a default value for kwargs
kwargs.setdefault('var', True)
Using for loop can set multiple default values.
for key, val in {'var1': 1, 'var2': 2}.items():
kwargs.setdefault(key, val)
kwargs
attribute
class foo:
def __init__(self, **kwargs):
kwargs.setdefault('var1', 1)
self.kwargs = kwargs
def print(self):
print(self.kwargs['var1']
a = foo()
a.print()
# 1
Inherit kwargs
class foo2(foo):
def __init__(self, **kwargs):
kwargs.setdefault('var1', 2)
super().__init__(**kwargs)
def print(self):
print(self.kwargs['var1'])
a2 = foo2()
a2.print()
# 2
The new default value has to be set before initiating super class, otherwise the parent default value will be used.
a2 = foo2(var1=3)
a2.print()
# 3