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?
1
  • For a practical system you probably want list to be an attribute of Person rather then inherit from list. Commented Jan 27, 2016 at 1:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.