如何访问列表中的实例对象并在其中显示数据?在python

问题描述 投票:0回答:1
class Bank:

    def __init__(self, name, balance=0):
        self.name = name
        self.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 = isbn
        self.title = title
        self.author = author
        self.publisher = publisher
        self.pages = pages
        self.price = price
        self.copies = copies

    def 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 True
        else:
            return False

    def shell(self):
        for i in range(self.copies, 0):
                    if self.copies == 0:
                        print('the book is out of stock')
                    else:
                        self.copies -= 1
                        print(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())

如何访问列表中的实例对象并显示它们?

<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>

它显示实例对象声明中的书,以及为什么main.Book对象位于0x00000000007A7400>显示__str____repr__是否在其中使用?

如果我从最后一行中删除评论并在第二行中评论,则>]

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

class Bank:def __init __(self,name,balance = 0):self.name =名称self.balance = balance#def Display_details(self):#print(self.name),#print(self ....

python list pycharm instance instance-variables
1个回答
1
投票

您面临的问题是,当您要打印方法返回的内容或让该方法为您打印时,您已经打印了方法i.display_text本身。

© www.soinside.com 2019 - 2024. All rights reserved.