我需要为一个程序创建两个类,该程序接受书籍、标题、作者、页数的输入变量,并查看它是否已检出,然后以下列格式将书籍添加到字典中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()
我在类库中的函数中的 for 循环似乎有问题__str__(self)
(想法是我希望循环遍历集合中的任何一本书),但我不确定问题是什么。这是我收到的错误消息:
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