You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类实例列表属性独立修改问题:图书馆管理系统开发咨询

图书馆管理系统:修改可借书籍列表时馆藏列表同步变化的问题

问题原因

在Python中,列表属于可变容器对象。当你在__init__方法中执行self.books = listOfBooks时,并没有创建新的列表,只是让self.books和self.listBooks这两个变量指向了内存中同一个列表对象。因此,当你调用self.books.remove(bookName)修改这个列表时,self.listBooks指向的是同一个对象,自然也会随之变化。

解决方案

要让self.books成为独立于self.listBooks的列表,需要在初始化时创建传入列表的副本。有几种常见的实现方式:

  • 使用列表构造函数:self.books = list(listOfBooks)
  • 使用列表的copy()方法:self.books = listOfBooks.copy()
  • 使用切片语法:self.books = listOfBooks[:]

修正后的完整代码

# 创建Library类及属性
class Library:
    def __init__(self, listOfBooks):
        self.listBooks = listOfBooks
        # 创建列表副本,使两个属性指向独立的列表对象
        self.books = list(listOfBooks)

    # 展示馆藏全部书籍
    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)

    # 借书功能
    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.')

# 创建图书馆实例
centralLibrary = Library(['C', 'C++', 'Algorithms', 'The Jungle Book', 'Heidi'])
# 测试代码
centralLibrary.displayBooks()
centralLibrary.borrowBook('The Jungle Book')
centralLibrary.displayBooks()

修改后,self.books的操作将不会影响self.listBooks,displayBooks方法可以始终展示完整的馆藏列表。

内容的提问来源于stack exchange,提问作者CodingP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 05:35:17