作为一项作业,我正在尝试创建两个类:一个类 ,Book
查看是否已签出一本书并返回书中的标题、作者和页码(这些是输入变量)和另一个类,称为Library
,将标题-作者对添加到字典中,并查看是否已签出某些特定书籍。每次尝试运行它时,我都会收到一条错误消息。我该如何解决这个奇怪的错误?
这是我的代码:
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
class Library:
def __init__(self):
collection = {}
def addExistingBook(self, book):
collection[book.title] = book.author
def addNewBook(self, title, author, pages):
new_book = Book(title, author, pages)
collection[title] = new_book.author
def change_checked_out_status(self, title):
if title in collection.keys():
title.change_value_of_checkedOut()
else:
print("This book is not in the collection.")
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)
main()
这是我尝试运行它时发生的情况:
Enter the title of the book. The Count of Monte Cristo
Enter the author of the book. Alexandre Dumas
Enter the number of pages in the book. 1250
Traceback (most recent call last):
File "C:/Python33/Class Programs/book_library_classes.py", line 56, in <module>
main()
File "C:/Python33/Class Programs/book_library_classes.py", line 54, in main
myLib.addExistingBook(myBook)
File "C:/Python33/Class Programs/book_library_classes.py", line 36, in addExistingBook
collection[book.title] = book.author
NameError: global name 'collection' is not defined