【问题标题】:updating class object from main function Python从主函数 Python 更新类对象
【发布时间】:2021-04-29 15:26:46
【问题描述】:

我有一个图书库程序,它的类读取包含@​​987654321@ 和name 的文件并将它们分配给self 对象作为idcard holder。然后有借书的自我对象,所以我可以识别哪个用户借了哪本书。 问题出在main 函数中,当用户还书时,我不知道如何更新自我借书对象以从对象中删除该书,因此自我id 将没有书借给它。

这是类的外观:

    #loan time length is 3 weeks by default
    LOAN_TIME = 3
    
    class Librarycard:
    
        def __init__(self, card_id, card_holder):
    
    
            self.__id = card_id
            self.__holder = card_holder
    
            #a dictionary that will contain the full book : loan time, updated in later function
            self.__loan = {}
    
        def return_book(self, book):
    
            del self.__loan[book]
            print('returned')
            return

这是我的main功能部分,涉及图书借阅:

    def main():
    
        command = input("Command: ")
        
        #borrowed books main list to check if book borrowed or not
        borrowed_books = []
        
                if command == "R":
        
                    book = input("Book code: ")
        
                    if book not in borrowed_books:
                        print('This book has not been borrowed by anyone')
        
                    else:
                        del borrowed_books[book]
                        print('book returned')
                        
                        # this is where I try to enter the function from the class to update the object 
                        # dictionary 
                        book.return_book(book)
    
    if __name__ == "__main__":
        main()

【问题讨论】:

    标签: python function class dictionary object


    【解决方案1】:

    这里有几个问题。

    首先,来自输入的书是一个字符串,而不是实际的书类。所以,当调用book.return_book(book)时,编译器在string类中寻找方法return_book(显然不存在)。

    其次,borrowed_books 永远不会在主类中更新,因此用户永远不会归还任何书籍。

    第三,不要在 Class 中使用 del,而是使用 self.__loan.pop(book)。它是内置的python函数,是删除书的更好方法。

    最后,骆驼案问题很多

    这是最终代码可能的样子。

    class LibraryCard:
        def __int__ (self, card_id, card_holder):
            self.card_id=card_id
            self.__card_holder=card_holder
            self.checked_out={}
        def return_book (self, book_id):
            popped = self.checked_out.pop(book_id, "Book was already returned, or was never checked out")
            if (popped != "Book was already returned, or was never checked out"): 
                print("Book returned: "+popped)
            else:
                print(popped)
        def isCard(self, id, name):
            return self.card_id==id and self.__card_holder==name
    
    
    def main():
        cards = {}
        while (true):
            command = input("To check out a book press \"C\", to return a book press \"R\" (without the quotes):\t")
            print("Whether or not you have an account, please follow the instructions below")
                card_id=input("Enter your card id:\t")
            user_name=input("For security purposes, enter your name:\t")
            if (user_id not in cards):
                print("Welcome to Library Services")
                cards[user_id] = LibraryCard(card_id, user_name)
            if (not cards[user_id].isCard(user_id, user_name)):
                print("Wrong user name or user id, please retry")
                continue
            if (command=="C"):
                book=input("Enter the name of the book you would like to check out: ")
                cards[user_id].checked_out[book]=3
                print("Checked out successfully!")
            else:
                book=input("Enter the name of the book you would like to return: ")
                cards[user_id].return_book(book)
                
                
            
    
     
    

    【讨论】:

    • 感谢 karma 的评论,我想我应该多提一下,我写的代码是完整代码的一部分,我跳过了写它的部分,因为它们与我的确切位置无关有问题。第二部分,我的努力是在不使用用户的任何 ID 的情况下专门归还图书,就像在实际图书馆中发生的那样,然后更新包含类中贷款的对象,如果我能够使用 ID,那将很容易,但我必须不这样做。
    • 图书馆的工作方式是每本书都有一个唯一的代码,即使这本书是相同的。因此,如果两本书相同,它们仍然会有不同的代码。我建议在这种情况下制作一个书籍类,并使用列表,而不是字典。
    【解决方案2】:
    class Librarycard:
    
        def __init__(self, card_id, card_holder):
            self.__id = card_id
            self.__holder = card_holder
    
            # a dictionary that will contain the full book : loan time, updated in later function
            self.__loan = {'tttt': {},"uuuu":{}}
    
        def return_book(self, book):
            del self.__loan[book]
            print('returned')
            return
    
    
    def main():
        # command = input("Command: ")
        command = "R"
    
        # borrowed books main list to check if book borrowed or not
        borrowed_books = ["tttt","aaaa"]
    
        if command == "R":
    
            # book = input("Book code: ")
            book = "tttt"
            if book not in borrowed_books:
                print('This book has not been borrowed by anyone')
    
            else:
                borrowed_books.remove(book)
                print('book returned')
    
                library_book = Librarycard('card_id', 'you know holder')
                print("before  ",library_book._Librarycard__loan)
                library_book.return_book(book)
                print("after ",library_book._Librarycard__loan)
    
    
    if __name__ == "__main__":
        main()
    
    C:\Users\sharp\AppData\Local\Programs\Python\Python39\python.exe C:/Users/sharp/Desktop/project/testid.py
    book returned
    before   {'tttt': {}, 'uuuu': {}}
    returned
    after  {'uuuu': {}}
    
    Process finished with exit code 0
    

    【讨论】:

    • 你应该在 del 或 pop 之前检查元素。我刚刚编辑了我的答案。
    • 现在错误消失了,但是借书ID上的self对象仍然包含该书,所以基本上该功能在那里但没有从字典中删除该书。
    • 我在我的电脑上做了一个测试~~所以结果:tttt已经被删除了。
    • 这很有趣,因为我再次尝试了您的方法,但仍然给我错误,我认为这可能是我在功能方面的一些冲突,但再次感谢您的帮助!跨度>
    【解决方案3】:

    我已经修复了它,我在主函数中添加了一个连接类的新变量,然后循环运行到类的类键中的所有卡,最后用那个键我激活了退货簿功能。

    主要问题是我没有创建要从中删除 bookID 的访问权限。但是一旦使用 for 循环激活,我就能够访问所有 ID'S 对象并从拥有它的那个中删除这本书。

    以下是与此问题相关的特定部分的代码:

    
        def main():
        
            #function that reads the text file and assign the card ids and card holders as a 
            #dictionary.
            library = read_card_data("library.txt")
        
        
             while True:
             command = input("Command: ")
        
                if command == "R":
        
                    book = input("Book code: ")
        
                    if book not in borrowed_books:
                        print('This book has not been borrowed by anyone')
        
                    else:
                        del borrowed_books[book]
        
                        for card in library.keys():
                            library[card].return_book(book)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多