将新对象附加到单独变量中的列表中

发布于 2025-02-09 07:17:08 字数 2977 浏览 1 评论 0原文

我对如何将新对象附加到列表中有些困惑。我觉得我正在考虑它,但是让我知道我在这里是否在正确的轨道上。

编辑:删除旧代码

要清楚,我不想直接编辑Display()中引用的文本文件(然后读出),我想使用附录方法添加一个列表结尾的新书。我使用半隆通过拆分来获得对象,因此,当我添加新书时,他们是否还会有分号呈现以匹配列表的其余部分?

编辑:这是我现在拥有的。

class Book: 

    def __init__(self, title, author, isbn, callnumber, stock, loaned):
        self.title = title
        self.author = author
        self.isbn = isbn
        self.callnumber = callnumber
        self.stock = stock
        self.loaned = loaned
        self.available = int(self.stock)-int(self.loaned)

    def getTitle(self):
        return self.title

    def getAuthor(self):
        return self.author

    def getISBN(self):
        return self.isbn

    def getCallNumber(self):
        return self.callnumber

    def getStock(self):
        return self.stock

    def getLoaned(self):
        return self.loaned

    def getAvailable(self):
        return self.available

    def __repr__(self):
        return self.title + '\t' + self.author + '\t' + self.isbn + '\t' + self.callnumber + '\t' + self.stock + '\t' + self.loaned + '\n'

    def inventory():
        fmtstring = '''{:<50}\t{:<20}\t{:<13}\t{:<13}\t{:<10}\t{:<10}\t{:<10}'''
        print(fmtstring.format("Name","Author","ISBN","Call Number","Stock","Loaned","Available"))
        books = []
        with open("books.txt", "r") as inventoryfile:
            for line in inventoryfile:
                strip_lines=line.strip()
                inventory = strip_lines.split(";")
                book = (Book(inventory[0],inventory[1],inventory[2],inventory[3],inventory[4],inventory[5]))
                books.append(book)
                print(fmtstring.format(*fields(book)))

    @staticmethod
    def input_book():
        title = input("Provide the title of the book> ")
        author = input("Provide the author of the book> ")
        isbn = input("Provide the ISBN of the book> ")
        callnumber = input("Provide the call number of the book> ")
        stock = input("Provide the stock of the book> ")
        return Book(title, author, isbn, callnumber, stock, 0)


And these are called on with menu options.

    while True:
        print()
        print("Westlands Book Inventory Management Subsystem")
        print("1. Display Inventory")
        print("2. Add a Book")
        print("3. Remove a Book")
        print("4. Export Inventory")
        print("5. Quit IMS")
        choice=eval(input("Select an option from the menu> "))
        if(choice==1):
            print()
            print("Displaying Westlands Books Inventory")
            print()
            Book.inventory()
        
        elif(choice==2):
            print()
            print("Adding a Book")
            print()
            Book.input_book()
            print()
            print('Book added successfully.')

这是我的代码的“安全”版本,不会破坏任何内容。我在各个地方尝试了附录命令,但似乎没有起作用。我似乎根本无法将输入返回到Input_books中。谢谢

I'm a little confused on how to append a new object to a list. I feel like I'm overthinking it, but let me know if I'm on the right track here.

EDIT: Removed old code

To be clear, I don't want to edit the text file referenced in display() directly (and then read off that), I want to use the append method to add a new book to the end of the list. I get the objects through a split using a semicolon, so when I'm adding new books, should they also have the semicolon present to match the rest of the list?

EDIT: Here is what I have now.

class Book: 

    def __init__(self, title, author, isbn, callnumber, stock, loaned):
        self.title = title
        self.author = author
        self.isbn = isbn
        self.callnumber = callnumber
        self.stock = stock
        self.loaned = loaned
        self.available = int(self.stock)-int(self.loaned)

    def getTitle(self):
        return self.title

    def getAuthor(self):
        return self.author

    def getISBN(self):
        return self.isbn

    def getCallNumber(self):
        return self.callnumber

    def getStock(self):
        return self.stock

    def getLoaned(self):
        return self.loaned

    def getAvailable(self):
        return self.available

    def __repr__(self):
        return self.title + '\t' + self.author + '\t' + self.isbn + '\t' + self.callnumber + '\t' + self.stock + '\t' + self.loaned + '\n'

    def inventory():
        fmtstring = '''{:<50}\t{:<20}\t{:<13}\t{:<13}\t{:<10}\t{:<10}\t{:<10}'''
        print(fmtstring.format("Name","Author","ISBN","Call Number","Stock","Loaned","Available"))
        books = []
        with open("books.txt", "r") as inventoryfile:
            for line in inventoryfile:
                strip_lines=line.strip()
                inventory = strip_lines.split(";")
                book = (Book(inventory[0],inventory[1],inventory[2],inventory[3],inventory[4],inventory[5]))
                books.append(book)
                print(fmtstring.format(*fields(book)))

    @staticmethod
    def input_book():
        title = input("Provide the title of the book> ")
        author = input("Provide the author of the book> ")
        isbn = input("Provide the ISBN of the book> ")
        callnumber = input("Provide the call number of the book> ")
        stock = input("Provide the stock of the book> ")
        return Book(title, author, isbn, callnumber, stock, 0)


And these are called on with menu options.

    while True:
        print()
        print("Westlands Book Inventory Management Subsystem")
        print("1. Display Inventory")
        print("2. Add a Book")
        print("3. Remove a Book")
        print("4. Export Inventory")
        print("5. Quit IMS")
        choice=eval(input("Select an option from the menu> "))
        if(choice==1):
            print()
            print("Displaying Westlands Books Inventory")
            print()
            Book.inventory()
        
        elif(choice==2):
            print()
            print("Adding a Book")
            print()
            Book.input_book()
            print()
            print('Book added successfully.')

This is the "safe" version of my code that doesn't break anything. I've tried the append command in various places but doesn't seem to be working. I can't seem to return what was input into input_books at all. Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

屌丝范 2025-02-16 07:17:08

您从用户输入中创建book的函数应该只是返回 book而不是尝试将其添加到列表中(主要是因为:什么列表?)。如果这是book上的方法,则应该是静态方法(或类方法),而不是实例方法,因为它的目的是 create 一个实例。例如:

@staticmethod
def input_book():
    title = input("Provide the title of the book> ")
    author = input("Provide the author of the book> ")
    isbn = input("Provide the ISBN of the book> ")
    callnumber = input("Provide the call number of the book> ")
    stock = input("Provide the stock of the book> ")
    return Book(title, author, isbn, callnumber, stock, 0)

现在外部您的book类,您可以做:

books = []
while True:
    print()
    print("Westlands Book Inventory Management Subsystem")
    print("1. Display Inventory")
    print("2. Add a Book")
    choice = input("Select an option from the menu> ")
    if choice == "1":
        print(books)
    if choice == "2":
        print()
        print("Adding a Book")
        print()
        books.append(Book.input_book())
        print()
        print('Book added successfully.')

请注意,books不是book,这是 book s 的 列表

Your function that creates a Book from user input should just return that Book rather than trying to add it to a list (primarily because: what list?). If it's a method on Book, it should be a static method (or a class method), not an instance method, since the point of it is to create an instance. For example:

@staticmethod
def input_book():
    title = input("Provide the title of the book> ")
    author = input("Provide the author of the book> ")
    isbn = input("Provide the ISBN of the book> ")
    callnumber = input("Provide the call number of the book> ")
    stock = input("Provide the stock of the book> ")
    return Book(title, author, isbn, callnumber, stock, 0)

Now outside your Book class, you can do:

books = []
while True:
    print()
    print("Westlands Book Inventory Management Subsystem")
    print("1. Display Inventory")
    print("2. Add a Book")
    choice = input("Select an option from the menu> ")
    if choice == "1":
        print(books)
    if choice == "2":
        print()
        print("Adding a Book")
        print()
        books.append(Book.input_book())
        print()
        print('Book added successfully.')

Note that books isn't a Book, it's a list of Books.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文