'Why does python code print memory location rather than the objects I want in my code?
I am new to python and am doing a question and I do not understand why the list I create using the Class doesn't work. I do not understand why it won't print the list properly and am wondering if someone could explain it to me.
My code:
SAMPLE_BOOKSHELF = [("The Da Vinci Code", "Dan Brown", "Doubleday", 2003, 489),
("The Lost Symbol", "Dan Brown", "Doubleday", 2009, 528),
("The Rough Guide to The Da Vinci Code", "Michael Haag", "Rough Guides", 2004, 256),
("The Da Vinci Hoax", "Carl E. Olsen & Sandra Miesel", "Ignatius Press", 2004, 100),
("The Da Vinci Cod", "A.R.R.R. Roberts", "Gollancz", 2005, 195)]
class Book:
def __init__(self, title, author, publisher, year, pages):
self.title = title
self.author = author
self.publisher = publisher
self.year = year
self.pages = pages
def main():
bookshelf = []
for (title, author, publisher, year, pages) in SAMPLE_BOOKSHELF:
b = Book(title, author, publisher, year, pages)
bookshelf.append(b)
for b in bookshelf:
print(x)
main()
Solution 1:[1]
Classes by default have no idea how you want to format them as strings when printed. You have to define the dunder method __str__ to tell it how you want to format it when printing:
class Book:
...
def __str__(self):
return f'{self.title}, {self.author}, {self.publisher}, {self.year}, {self.pages}'
The good thing here is that you can customize it as you desire, for example:
def __str__(self):
return f'[Book] Title: {self.title}, Author: {self.author}, Publisher: {self.publisher}, Year: {self.year}, Pages: {self.pages}'
One more thing to note is there is also the __repr__ method, which is for when you use Jupyter Notebook or the shell, where instead of printing you want to look at the representation.
Example in shell:
>>>> my_book = Book("The Da Vinci Code", "Dan Brown", "Doubleday", 2003, 489)
>>>> my_book
[Book] Title: The Da Vinci Code, Author: Dan Brown, Publisher: Doubleday, Year: 2003, Pages: 489
Solution 2:[2]
So what I can see from your code is 3 problems, basic fault is that you have undefined values such as li in your appending part to the list as the list you defined is bookshelfand x in your print function so you should have errors there and secondly what you did is make b an instance which has only initialized the values you want to use in your class and did not make a method in your class which can be used to return a value from that function in the form of what you would like your string to look like. You can use __str__ special method which will help you represent your string in the way you desire.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
