How To Access Instance Object In List And Display There Data? In Python
Solution 1:
The problem you're facing is you've printed the method i.display_text
itself when what you want is to either print what the method returns or let the method print for you.
You need to decide where you want the print()
function to occur. You can either call display()
and let it print for you or have display return the text and print it.
Generally I would advise you to not use print
inside your methods. Keep your class simple.
Option 1:
Don't call print in your loop and be sure to make i.display()
a call not a reference.
for i in book_list:
i.display()
Option 2:
Call print in your loop but have your method return the string. (I took some liberties with formatting)
defdisplay_text(self):
return (
f"isbn = {self.isbn} \n"f"title = {self.title} \n"f"price = {self.price} \n"f"copies = {self.copies} \n"
)
...
for i in book_list:
print(i.display_text())
Option 3:
Use a __str__
or __repr__
method on the class and simply print the instance. This is useful during debugging as well as simply printing the information on screen. You'll be able to identify which Book instance is which much easier.
def__str__(self):
return ( f"Book<{self.isbn} '{self.title}' ${self.price}{self.copies}>")
...
for i in book_list:
print(i)
will output this:
Book<957-4-36-547417-1 'Learn Physics' $200 10>
Book<652-6-86-748413-3 'Learn Chemistry' $220 20>
Book<957-7-39-347216-2 'Learn Maths' $300 5>
Book<957-7-39-347216-2 'Learn Biology' $200 6>
Bonus points:
You could also make your display()
method a @property
which allows you to reference it without the normal call parenthesis. See properties.
example:
@propertydefdisplay_text(self):
return (
f"isbn = {self.isbn} \n"f"title = {self.title} \n"f"price = {self.price} \n"f"copies = {self.copies} \n"
)
...
for i in book_list:
print(i.display_text)
Post a Comment for "How To Access Instance Object In List And Display There Data? In Python"