在对象中创建列表(book / patron waitlist)

时间:2014-05-15 03:53:30

标签: python list methods instantiation

我有一个家庭作业来创建一个"库"有一个赞助班和书籍班。这个图书馆应该允许人们查看最多3本书,并且如果书已经签出,则将书添加到顾客的候补名单中。书籍退回后,应自动检查等候名单上的第一个人。我似乎无法让清单发挥作用。这是我的代码:

class Patron(object):
def __init__(self,name,booksOut=0):
    self._name=name
    self._booksOut=booksOut

def getBooksOut(self):
    return self._booksOut

def __str__(self):
    result="Name: "+self._name+"\n"
    result+="Books Out: "+str(self._booksOut)+"\n"
    return result


class Book(object):
def __init__(self,title,author,owner=None):
    self._title=title
    self._author=author
    self._owner=owner
    self._queue=[] #Here is the empty list I'm using... but it doesn't seem to be working.

def setOwner(self,owner):
    self._owner=owner

def getOwner(self):
    return self._owner

def borrowMe(self, patron):
    if self._owner != None:
        return "This book is not available. You've been added to the queue.\n"
        self._queue.append(patron)
        print(str(self._queue)) #I can't even get the list to print, so I'm feeling like I didn't create it correctly
    else:
        if patron.getBooksOut()>=3:
            return "You have too many books checked out!"
        else:
            self.setOwner(patron)
            patron._booksOut+=1
            return "You have successfully checked this book out."

def returnMe(self):
    if len(self._queue)==0:
        self.setOwner(None)
        return "Your book has been returned."
    else:
        return "Your book has been given to: "+str(self._queue[0])
        self.borrowMe(self._queue[0]) #Here is where I'm trying to automatically borrow the book to the first person in the waitlist

def __str__(self):
    result="Title: "+self._title+"\n"
    result+="Author: "+self._author+"\n"
    if self._owner != None:
        result+="Owner: "+str(self.getOwner())
    else:
        result+="Owner: None"
    return result


def main():
"""Tests the Patron and Book classes."""
p1 = Patron("Ken")
p2 = Patron("Martin")
b1 = Book("Atonement", "McEwan")
b2 = Book("The March", "Doctorow")
b3 = Book("Beach Music", "Conroy")
b4 = Book("Thirteen Moons", "Frazier")
print(b1.borrowMe(p1))
print(b2.borrowMe(p1))
print(b3.borrowMe(p1))
print(b1.borrowMe(p2))
print(b4.borrowMe(p1))
print(p1)
print(b1)
print(b4)
print(b1.returnMe())
print(b2.returnMe())
print(b1)
print(b2)

我已经注释了包含列表创建的部分(在书籍类的 init 中),并且我尝试打印列表以进行一些错误检查(在borrowMe方法中) )以及我试图自动将书借给等候名单/队列中的第一个人(在returnMe方法中)。

感谢任何见解。

1 个答案:

答案 0 :(得分:1)

if self._owner != None:
        return "This book is not available. You've been added to the queue.\n"
        self._queue.append(patron)
        print(str(self._queue))

您正在return之后打印。 return之后不会执行任何操作。将其更改为print。同样在Patron课程中,将__str__更改为__repr__。否则,它将打印一个内存地址列表。此外,print(str(self._queue))是多余的,您可以直接打印列表。

相关问题