This is from the book head first python (pg 208 chapter 6). Initially I saw an example in the book of the initialisation of the subclass as so:
class AthleteList(list):
def __init__(self, a_times=[]):
list.__init__([])
self.extend(a_times)
When I came to writing my own version I thought I could skip the extend
step:
class AthleteList(list):
def __init__(self, a_times=[]):
list.__init__(a_times)
When it comes to printing the list:
test = AthleteList([1,2,3])
print(test)
The output is []
, so there is something wrong with the initialisation. When searching around, in every case I found I saw it necessary to initialise the superclass by explicitly passing self
:
class AthleteList(list):
def __init__(self, a_times=[]):
list.__init__(self, a_times)
Which makes more sense: the list superclass needs the object itself passed as an argument so that it can initialise its list values. Except why wasn't self
needed in the very first example (which does actually work)? Even if I am initialising it with an empty list I still surely need to pass the self
object so that self
's list is made empty. I don't even need to initialise it to the empty list first, it seems to do it by default, and I can just extend later:
class AthleteList(list):
def __init__(self, a_times=[]):
self.extend(a_times)