【问题标题】:How to change an instance attribute without changing another instance attribute assigned the same value?如何在不更改分配相同值的另一个实例属性的情况下更改实例属性?
【发布时间】:2023-01-01 04:45:38
【问题描述】:

我想使用 Python 3.10.8 和 OOP 方法创建一个图书馆管理系统。

我想制作两个实例属性:

1)书单:包含图书馆馆藏中可用的书籍列表(目录)

2.)图书: 包含图书馆中尚未由其他人发行的书籍清单。

我做了一个借书的功能(借书) 从存储在的列表中删除借来的书图书.但不知何故列表存储在书单也得到了我不想要的改变,因为我想要展示书籍功能显示图书馆馆藏的所有图书,而不仅仅是未发行的图书。

# Creating Library Class and the 2 attributes
    class Library:
      def __init__(self, listOfBooks):
        self.listBooks = listOfBooks
        self.books = listOfBooks

# Creating function to display books available in library collection
    def displayBooks(self):
        print('Following is the list of books in the library catalogue:')
        for index, book in enumerate(self.listBooks):
            print(index+1, book)

# Creating function to borrow books
    def borrowBook(self, bookName):
        if bookName in self.listBooks:
            if bookName in self.books:
                print(
                    f'{bookName} has been issued to you. Please keep it safe and return it within 30 days!')
       

                self.books.remove(bookName)
            else:
                print(
                    'Sorry the requested book is currently issued to someone else! Please try again later.')
        else:
            print(
                f'{bookName} is currently unavailable in our library catalogue. Sorry for the inconvenience.')
# Creating library object
    centralLibrary = Library(
    ['C', 'C++', 'Algorithms', 'The Jungle Book', 'Heidi'])
# Testing the code
    centralLibrary.displayBooks()
    centralLibrary.borrowBook('The Jungle Book')
    centralLibrary.displayBooks()

我如何更改里面的列表图书并同时将列表保留在里面书单因为它是?

还有为什么list在里面书单无论如何改变?

我正在使用 VS Code(版本 1.72.2)作为 IDE。

【问题讨论】:

    标签: python oop instance-variables


    【解决方案1】:

    使 listOfBooks 成为一个类变量,它使用一种方法将您传递给第一个实例的书籍列表附加到类中,该方法不会在每个实例中更新:

    class Library:
        listOfBooks = []
        def __init__(self, listOfBooks):
            self.books = listOfBooks
            self.make_class_listOfBooks(listOfBooks)
    
        def make_class_listOfBooks(self, starting_list_of_books):
            for index, book_name in enumerate(starting_list_of_books):
                self.__class__.listOfBooks.append(book_name)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 2021-12-17
      • 1970-01-01
      • 2021-12-07
      • 2021-09-05
      • 1970-01-01
      相关资源
      最近更新 更多