So, I came across this when reviewing some code at my company, the interesting problem was trying to avoid duplicate default values in subclasses. Let me explain:
class SuperClass:
def __init__(self, arg1, arg2):
pass
class Subclass(SuperClass):
def __init__(self, arg1, arg2='default_value'):
super().__init__(arg1, arg2)
class Subclass2nd(SuperClass):
def __init__(self, arg1, arg2='default_value'):
super().__init__(arg1, arg2)
So, the idea is that arg2
needs to have a default value so when Subclass
and Subclass2nd
are initialized, they don't require a value for arg2
.
But, due to DRY principle, it is good to have that default value defined only once in case you ever have to change that. But, it is not entirely obvious since if you end up putting that default value in SuperClass
with no default value in Subclass
then it becomes a required argument for it.
class SuperClass:
def __init__(self, arg1, arg2='default_value'):
pass
class Subclass(SuperClass):
def __init__(self, arg1, arg2):
super().__init__(arg1, arg2)
So, what is the right way to do this? You don't look at arg2 in Subclass
!
class Subclass(SuperClass):
def __init__(self, arg1, *args, **kw):
super().__init__(arg1, *args, **kw)
Alternative ways
class Subclass(SuperClass):
def __init__(self, arg1, arg2=None):
args = dict(arg1=arg1)
if arg2:
args['arg2']=arg2
super().__init__(**args)
Let me know if you have more ways to do this :)