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 trialHenry Lin
11,636 PointsThe difference between str(bc.books) and str(bc.books[0])?
In the class of Book of books.py, Kenneth overrode the str function which would return a books info. However, when I tried to look up both books' info in books, it returned information about memory instead of the string representation of books.
Here is my understanding so far:
In the Bookcase class, the @classmethod create_bookcase() returns an instance of Bookcase, and during the process, it also extracts info from book_list and passes it to Book class so that every time the for loop executes, it creates a Book instance and stored it in books[] list. Therefore, by the time the code gets executed completely, there is a Bookcase instance, and two Book instances(based on the video).
Thus, when we type bc, the console would show the object info of Bookcase. When we use the overrode method str(bc.books), I thought it would have returned the two books "real info" (title, author) because bc.books invoked the attributes in Book class. Hence, str in Book class should take place.
But it's not the case !! Can someone explain this question?
1 Answer
Chris Freeman
Treehouse Moderator 68,457 PointsGreat question! Let's look at each case
str(bc)
--> Since bc
has no __str__
, so it reports out the object information
str(bc.books)
--> bc.books
is a list that has a built-in __str__
method. However, this __str__
method has the default behavior of calling __repr__
on each of the items in the list. So, only the object information is shown. More in the docs.
str(bc.books[0])
--> bc.books[0]
is a reference to a Book
object that has it's own __str__
method so the output is "title by author"
Post back if you have more questions. Good Luck!!
Henry Lin
11,636 PointsHenry Lin
11,636 PointsThank you so much! I got it now.