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:
- This line
list.__init__(a_books), doesn't actually initialize my instance's list of books. - I am supposed, according to the book, write
list.__init__([])instead. Why is this step necessary. - Why is there no reference to
selfinlist.__init__([])? How does Python know?
-
For a practical system you probably want list to be an attribute of Person rather then inherit from list.Penguin Brian– Penguin Brian2016年01月27日 01:04:35 +00:00Commented Jan 27, 2016 at 1:04
1 Answer 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'])
['how to bob']
Because list has a __str__ method.
answered Jan 27, 2016 at 1:00
user764357
Sign up to request clarification or add additional context in comments.
Comments
lang-py