【问题标题】:How do I get the return value of my __str__() function to print in my main?如何让我的 __str__() 函数的返回值在我的 main 中打印?
【发布时间】:2013-04-24 21:25:18
【问题描述】:

我需要为一个程序创建两个类,该程序接受书籍、标题、作者、页数的输入变量,并查看它是否已检出,然后按以下格式将书籍添加到字典中 dictionary[title] = author .然后我需要以这种格式在主函数中打印我的所有信息:“”title author pages checkOut。”我基本上需要在我的类中打印出我的__str__()函数的返回值。这是我的代码:

class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages
        self.checkedOut = False

    def checked_Out(self):
        print(self.checkedOut)
        return self.checkedOut

    def change_value_of_checkedOut(self):
        if self.checkedOut == False:
            self.checkedOut = True
            print("Switched from False to True.")
        elif self.checkedOut == True:
            self.checkedOut = False
            print("Switched from True to False.")

    def return_pages(self):
        print(self.pages)
        return self.pages

    def return_title(self):
        print(self.title)
        return self.title

    def __str__(self):
        return ("Title: " + self.title + "Author: " + self.author +
                "Pages: " + self.pages + "Checked Out Status: " +
                self.checkedOut)

class Library:
    def __init__(self):
        self.collection = {}

    def addExistingBook(self, book):
        self.collection[book.title] = book.author

    def addNewBook(self, title, author, pages):
        new_book = Book(title, author, pages)
        self.collection[title] = new_book.author

    def change_checked_out_status(self, title):
        if title in self.collection:
            title.change_value_of_checkedOut()
        else:
            print("This book is not in the collection.")

    def __str__(self):
        for myBook in self.collection[myBook]:
            self.collection[myBook]
            self.collection[myBook] = self.author

            # I want to print this return value in my main
        return ("Title: " + self.title + "Author: " + self.author
                + "Pages: " + self.pages + "Checked Out Status: " + self.checkedOut)

def main():
    title = str(input("Enter the title of the book. "))
    author = str(input("Enter the author of the book. "))
    pages = int(input("Enter the number of pages in the book. "))
    myBook = Book(title, author, pages)
    myLib = Library()
    myLib.addExistingBook(myBook)
    myLib2 = Library()
    myLib3 = myLib2.__str__()
    print(myLib3)

main()

在类库中我的__str__(self) 函数中的 for 循环似乎有问题(我希望循环遍历集合中的任何一本书)但我不确定是什么问题是。这是我收到的错误消息:

Enter the title of the book. A Tale of Two Cities
Enter the author of the book. Charles Dickens
Enter the number of pages in the book. 434
Traceback (most recent call last):
  File "C:\Python33\Class Programs\lab8.py", line 71, in <module>
    main()
  File "C:\Python33\Class Programs\lab8.py", line 68, in main
    myLib3 = myLib2.__str__()
  File "C:\Python33\Class Programs\lab8.py", line 54, in __str__
    for myBook in self.collection[myBook]:
UnboundLocalError: local variable 'myBook' referenced before assignment

【问题讨论】:

    标签: python class


    【解决方案1】:

    您正在遍历字典的键,您不应该尝试在循环语句中传递键:

    def __str__(self):
        for myBook in self.collection:
    

    目前尚不清楚您要对该循环做什么。然后您访问self.collection[myBook] 而不对返回值做任何事情,然后您将替换self.authorself 上不存在,这仍然是库),然后你返回与__str__() 结果完全不同的东西。

    认为您想在此处创建图书馆图书列表:

    def __str__(self):
        return ', '.join('{} - {}'.format(title, author) for title, author in self.collection.items())
    

    现在您返回一个以逗号分隔的列表,其中包含您收藏中的所有标题和作者。

    那里发生了 3 件事:

    • 使用生成器表达式,我们遍历字典.items() method;这将为字典中的所有内容生成 (key, value) 对。
    • 每个键和值都传递给str.format() method,使用字符串作为模板,在您的self.collection 字典中存储的标题和作者对之间放置- 破折号。
    • 整个循环传递给str.join() method;此方法从给定的序列中获取所有字符串,并将它们与它们之间的', ' 逗号连接在一起。

    接下来,您正在创建一个 empty 库,然后打印__str__() 方法的输出;无需显式调用,print() 会为您执行此操作。不要创建新库,只需打印您已有的库即可:

    myLib = Library()
    myLib.addExistingBook(myBook)
    print(myLib)
    

    【讨论】:

    • 当我将其更改为您的建议并运行程序时,在我输入输入变量后,程序只返回 None。像这样:输入书名。两个城市的故事 请输入本书的作者。查尔斯狄更斯 输入书中的页数。第434章
    • 知道了!谢谢。但是你能简要解释一下你为我建议的 return 语句是什么意思吗?我以前从未见过。
    • ".".join(iteratable) 将可迭代对象与字符串连接起来。有关.format 的信息,请参阅食谱mkaz.com/solog/python-string-format
    • @IvanLesiv:添加了更详细的说明以及方法文档的链接。
    【解决方案2】:

    我想你想改变

    def __str__(self):
            for myBook in self.collection[myBook]:
                self.collection[myBook]
                self.collection[myBook] = self.author
    

    def __str__(self):
            for myBook in self.collection.keys():
                self.collection[myBook]
                self.collection[myBook] = self.author
    

    【讨论】:

    • Python 字典没有大写的.Keys() 方法。
    • 接下来,见my comment on another answer here;您实际上并不需要使用.keys()。根据my answer,其余代码毫无意义,尤其是在__str__ 方法的上下文中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 2015-12-01
    • 2017-05-06
    • 2018-04-22
    • 1970-01-01
    相关资源
    最近更新 更多