Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSuraj Shah
1,055 PointsBookCase uses the Book class without calling parent class?
In the BookCase class, we inherit from the Book class to get the title and author and append it to the book list.
books.append(Book(title, author))
but when we create the BookCase class, we don't use:
class BookCase(Book)
how is it that the code still works?
full code here:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return "{} by {}".format(self.title, self.author)
class BookCase:
def __init__(self, books=None):
self.books = books
@classmethod
def create_bookcase(cls, book_list):
books = []
for title, author in book_list:
books.append(Book(title, author))
return cls(books)
1 Answer
Chris Freeman
Treehouse Moderator 68,423 PointsTo clarify, the class BookCase
does not inherit from the class Book
as noted in the declaration line
class BookCase:
BookCase
has one attribute books
that is a list of Book objects. During BookCase.__init__
, new Book
objects are added to the attribute BookCase.books
.
Post back if you need more help. Good luck!!!
Suraj Shah
1,055 PointsSuraj Shah
1,055 PointsChris Freeman , thanks for your response.
I guess my confusion was in the BookCase class, we have a class method which has a line books.append(Book(title, author)), we are calling the Book class that we wrote earlier in the programme.
If I were writing the code from scratch, I would have written class BookCase(Book)
Just trying to understand why we did not do this here.
Chris Freeman
Treehouse Moderator 68,423 PointsChris Freeman
Treehouse Moderator 68,423 PointsThe difference is that we want
Bookcase
to be it's own class but include references to another class. This is a structural hierarchy of classes instead of an inherited hierarchy of class definition.Chris Freeman
Treehouse Moderator 68,423 PointsChris Freeman
Treehouse Moderator 68,423 PointsGreat question by the way!