Python 3.4.3 - 具有相同信息的多个对象

标签 python

在我的

class Library(object):

def __init__(self):
     self.books = []


def add_book(self, book):
    if book.get_title() not in self.books:
        self.books.append(book)
else:
    print("This book is already added.")

然后在我的 main() 中我得到:

if command == "add":

    title = input("Please type in the title of the book:")

    author = input("Please type in the author of the book:")

    year = int(input("Please type in the year of the book:"))

    my_lib.add_book( Book(title, author, year) )

    print("The book has been added.")

elif command == "view":
    my_lib.view_library()

elif command == "get":

    book_title = input("Please type in the title of the book:")
    book = my_lib.find_book(book_title)
    if book != False:
        print("Here's the book:")
        print("Title:", book.get_title() + ".\nAuthor:",
          book.get_author() + ".\nYear:",
          str(book.get_year()) + ".\nBorrowed:",
          str(book.get_borrowed()) + ".\n")


    else:
        print("This book does not exist.")

elif command == "borrow":
    book_title = input("Type in the title of the book you want to borrow:")
    book = my_lib.find_book(book_title)
    if book != False and book.get_borrowed() == None:
        pass

    elif book == False:
        print("This book does not exist in our catalog!")
    else:
        print("This book is already borrowed!")

我的问题是,当我添加多本具有相同标题、作者和年份的书籍时,我只能借其中一本。可能是一个简单的解决方案,但我被困住了。我还想使用另一个名为 User 的类,我可以在其中存储所有人员的姓名,而不仅仅是在借用函数中执行以下操作:

    ##name = input("Please type in your name:")
    ##book.set_borrowed(name)

我现在已经通行证了。我还有另一门课,就是书。与所有正常的 getter 和 setter 一起使用。

澄清一下,这不起作用:

def add_book(self, book):
    if book.get_title() not in self.books:
        self.books.append(book)

This doesnt work. I can still add a book with the exact same info including title!    

最佳答案

我认为你需要重新考虑你的计划。

如果您创建两本具有相同属性值的图书,客户将无法区分它们。

一种可能是为每本书添加一个唯一的 ID(使用 Book 类中随每本书增加的类变量)并使用此 ID 借书。另一种可能性是存储一种类型的书籍有多少本可用。您可以使用书籍类中的 int 计数器来实现这一点。如果添加了具有匹配属性的书籍,则增加它;如果计数器大于 0(= 书籍可用)并且调用“get”命令,则减少它。

这应该可以解决您的问题。

顺便说一句:setter 和 getter 不是 pythonic。在 python 中,您通常使用直接访问属性。如果您需要进一步处理(值检查等),您可以使用属性。

关于Python 3.4.3 - 具有相同信息的多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31313521/

相关文章:

Python Telegram Bot : Prompt for another input

python - numpy 行/列到一维向量?

__unicode__ 的 Python 字符串格式字符?

python - 我不明白为什么会出现 "too many values to unpack"错误

Python:日期时间模块使用 24 小时时钟的一天结束

Python 在到达调试点时退出,抛出 "called Tcl_FindHashEntry on deleted table"错误

python - 如何将不同类型的列插入到 numpy 数组中?

python - Pandas groupby : get max value in a subgroup

python - 多个子流程需要大量时间才能完成

python - 无法通过upip安装Micropython模块,错误信息不清楚