2

I just started learning Python, and created the following class, that inherits from list:

class Person(list):
    def __init__(self, a_name, a_dob=None, a_books=[]):
        #person initialization code
        list.__init__(a_books)
        self.name = a_name
        self.dob = a_dob

However, there are three things I don't understand:

  1. This line list.__init__(a_books), doesn't actually initialize my instance's list of books.
  2. I am supposed, according to the book, write list.__init__([]) instead. Why is this step necessary.
  3. Why is there no reference to self in list.__init__([])? How does Python know?
R.V.
  • 71
  • 4

1 Answers1

1

You need to make a super call to instantiate the object using the parents __init__ method first:

class Person(list):
    def __init__(self, a_name, a_dob=None, a_books=[]):
        #person initialization code
        super(Person, self).__init__(a_books)
        self.name = a_name
        self.dob = a_dob

print Person('bob',a_books=['how to bob'])

Gives the output:

['how to bob']

Because list has a __str__ method.