Why doesn't Python use the default argument values when initializing a superclass?
class Base:
def __init__(self, list=[]):
self.list = list
class Sub(Base):
def __init__(self, item):
Base.__init__(self)
self.list.append(item)
x = Sub(1)
y = Sub(2)
print x.list # prints [1, 2]
print y.list # prints [1, 2]
In this case, it seems that there is only one 'list' variable that's shared between the two instances of Sub. I can solve the issue by explicitly passing the value of 'list', i.e.:
class Base:
def __init__(self, list=[]):
self.list = list
class Sub(Base):
def __init__(self, item):
Base.__init__(self, list=[])
self.list.append(item)
x = Sub(1)
y = Sub(2)
print x.list # prints [1]
print y.list # prints [2]
Is there a way to avoid passing the argument explicitly in such cases? In my actual application, I have a lot of default values in my superclasses and it causes a lot of code duplication to pass them all again every time I initialize a subclass.