How to access instance object in list and display there data? in python

2024/11/17 9:55:29
class Bank:def __init__(self, name, balance=0):self.name = nameself.balance = balance# def Display_details(self):#     print( self.name),#     print(self.balance),#### def Withdraw(self, a):#     self.balance -= a#     print(f"Balance after withdrawn {self.balance}")### def Deposite(self, b):#     self.balance += b#     print(f"Balance after deposite {self.balance}")class Book:def __init__(self,isbn, title, author, publisher, pages, price, copies):self.isbn = isbnself.title = titleself.author = authorself.publisher = publisherself.pages = pagesself.price = priceself.copies = copiesdef display(self):print(f"isbn = {self.isbn}")print(f"title = {self.title}")print(f"price = {self.price}")print(f"copies = {self.copies}")def in_stock(self):if self.copies > 0:return Trueelse:return Falsedef shell(self):for i in range(self.copies, 0):if self.copies == 0:print('the book is out of stock')else:self.copies -= 1print(self.copies)book1 = Book('957-4-36-547417-1', 'Learn Physics','Stephen', 'CBC', 350, 200,10)
book2 = Book('652-6-86-748413-3', 'Learn Chemistry','Jack', 'CBC', 400, 220,20)
book3 = Book('957-7-39-347216-2', 'Learn Maths','John', 'XYZ', 500, 300,5)
book4 = Book('957-7-39-347216-2', 'Learn Biology','Jack', 'XYZ', 400, 200,6)book_list = [book1, book2, book3, book4]for i in book_list:print(i.display)
# print(book1.display())

How to access instance object in list and display them?

<bound method Book.display of <__main__.Book object at 0x0000000001D88880>>
<bound method Book.display of <__main__.Book object at 0x0000000001D88CD0>>
<bound method Book.display of <__main__.Book object at 0x0000000001D88BB0>>
<bound method Book.display of <__main__.Book object at 0x00000000007A7400>

its display the book from the instance object declaration and why the main.Book object at 0x00000000007A7400> is displayis there and use of __str__ and __repr__ in this?

if i remove the comment from the last line and comment the 2nd line

print(book1.display())

(venv) C:\Users\admin\PycharmProjects\ankitt>bank.py
isbn = 957-4-36-547417-1
title = Learn Physics
price = 200
copies = 10
None
Answer

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)

    def display_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:

    @propertydef display_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)
https://en.xdnf.cn/q/118822.html

Related Q&A

Using Class, Methods to define variables

I have a number of chemicals with corresponding data held within a database, how do I go about returning a specific chemical, and its data, via its formula, eg o2.class SourceNotDefinedException(Except…

Python Tkinter: Color changing grid of buttons?

I understand that you can make a button that can do some actions when clicked with Tkinter, but how can I just make a button that turns from one color to another when clicked? Then, from that, how do …

Writing a function that checks prime numbers

def primecheck(num): if num > 1: for i in range(2, num): if (num % i) == 0: return False breakelse: return TrueIm trying to make a function that checks if an input is prime or not. This code does …

Getting error code 1 while installing geopandas with pip

This is the error I get when trying to install geopandas using pip install geopandas. Im using Python 3.7.Collecting geopandasUsing cached https://files.pythonhosted.org/packages/24/11/d77c157c16909bd7…

Find if a sorted array of floats contains numbers in a certain range efficiently

I have a sorted numpy array of floats, and I want to know whether this array contains number in a given range. Note that Im not interested in the positions of the number in the array. I only want to k…

Django Operation error: (2026, SSL connection error: SSL_CTX_set_tmp_dh failed)

I can not start my django server after running a statement through manage.py for generating class diagrams from db. And I always get this error but I dont know how to deal with it. OperationalError: (2…

TypeError with module object is not callable

I have a test folder the structure within the folder__init.py__ aa.py test.pyfor aa.pyclass aa:def __init__(self,max):self.max=maxprint max+1def hello(self):print(max)for test.pyimport aa abc = aa(100)…

How to access the GUI output?

Im developing one test bench which runs multiple tests via python gui and prints the output as below.A Passed B Passed C Passed D Passed E PassedButton from gui should be changed to Passed only when A,…

Is it possible to have an api call another api, having them both in same application?

I have a python application running on my localhost:3978. Is it possible to make an api call to http://localhost:3978/api/users from http://localhost:3978/api/accounts? @routes.get("/api/accounts…

Find word near other word, within N# of words

I need an enumerating regex function that identifies instances in a string when Word 1 is within N# words of Word 2 For example, here is my dataframe and objective: Pandas Dataframe Input data = [[ABC…