代码倒数第九行 if copies: # key already exists
copies.append(item)
不是很理解这个append是什么意思。copies调动出来的不是ISBN码吗?,为什么可以用append方法?并且collection不是一个字典吗?怎么可以用列表的append添加呢?
class PublishedWork():
def __init__(self, isbn, title, authors, edition, bookType):
self.isbn = isbn
self.title = title
self.authors = authors
self.edition = edition
self.bookType = bookType # hardback, audiobook etc.
class LibraryItem():
def __init__(self, publishedWork, location):
if not isinstance(publishedWork, PublishedWork): # every library item must link to a specific work
raise Exception("expected parameter publishedWork to be instance of PublishedWork.")
self.publishedWork = publishedWork
self.location = location
self.available = True
def borrowItem(self):
if not self.available: # check it's possible to borrow the item
raise Exception("Cannot borrow this item because it is unavailable.")
self.available = False # show that the item is now not available
def returnItem(self):
self.available = True # this item is now available
class Library():
def __init__(self):
self.collection = {}
# when a new book is purchased this function is used to add it to the library
def addItem(self, item):
if not isinstance(item, LibraryItem):
raise Exception("expected parameter item to be instance of LibraryItem.")
# add item to the collection
isbn = item.publishedWork.isbn # isbn is used as key
copies = self.collection.get(isbn)
if copies: # key already exists
copies.append(item)
else:
self.collection[isbn] = [item] # create key
def numberOfCopies(isbn):
copies = self.collection.get(isbn)
if copies is None:
return 0 # key does not exist
return len(copies) # length of list is number of copies of this isbn