您在__init__
定义collection
作为一个局部变量:
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()
下面是当我尝试运行它会发生什么
def __init__(self):
collection = {}
但这并不奇妙地使它成为一个实例变量。你所要做的是明确的:
class Library:
def __init__(self):
self.collection = {}
def addExistingBook(self, book):
self.collection[book.title] = book.author
而且,我也不会做的方法是这样的:
def return_title(self):
print(self.title)
return self.title
他们混淆了直白book.title
属性的另一种层。
而且,你不需要写.keys()
。 if key in dictionary
是首选语法:
if title in self.collection:
在你的'__init__'集合中是一个局部变量。你需要做自我。集合'为它是一个实例变量 – RedBaron 2013-04-24 04:50:39
您需要在所有地方将'collection'更改为'self.collection'。 – 2013-04-24 04:51:26