链表实现Catalog按作者精确匹配(忽略大小写)报错排查
问题修正方案
关键错误分析
- 缺少add方法:Catalog类未实现
add方法,导致无法向目录中添加书籍。 - 错误的类型处理:
filter_by_author中误将Book实例当作字符串调用capitalize(),引发属性错误。 - 逻辑偏离需求:原方法逻辑错误,未实现“筛选匹配作者的书籍”功能,反而返回整个目录。
- __repr__格式错误:Book类的
__repr__方法末尾多了一个闭合括号,导致输出格式异常。
修正后的完整代码
class Book: def __init__(self, title, author, year): if not isinstance(title, str): raise Exception("title must be a string") if not isinstance(author, str): raise Exception("author must be a string") if not isinstance(year, int): raise Exception("year must be an integer") self.title = title self.author = author self.year = year def __eq__(self, other): if isinstance(other, Book): return self.title == other.title and \ self.author == other.author and \ self.year == other.year return NotImplemented def __repr__(self): # 修正格式错误,补充括号包裹年份 return f"{repr(self.title)} by {repr(self.author)} ({self.year})" class Catalog: def __init__(self): self.lst = [] # 添加缺失的add方法 def add(self, book): if not isinstance(book, Book): raise Exception("Only Book instances can be added to Catalog") self.lst.append(book) def filter_by_author(self, author): # 将输入作者名转为大写,统一大小写进行比较 target_author = author.upper() # 遍历目录中的每本书,筛选作者匹配的书籍 return [book for book in self.lst if book.author.upper() == target_author] # driver b1 = Book("1984", "George Orwell", 1949) b2 = Book("Brave new world", "Aldous Huxley", 1932) b3 = Book("El aleph", "Jorge Louis Borges", 1949) b4 = Book("The devils of Loudun", "Aldous Huxley", 1952) cat = Catalog() cat.add(b1) cat.add(b2) cat.add(b3) cat.add(b4) la = cat.filter_by_author("aldous huxley") assert la == [b2, b4]
核心修改说明
- 新增add方法:确保只有Book实例能被添加到目录中,维护数据类型一致性。
- 重构filter_by_author:
- 将输入的作者名转为大写(也可使用小写),实现大小写不敏感匹配。
- 使用列表推导式遍历目录,筛选出作者名转大写后与目标作者一致的书籍。
- 修正__repr__格式:调整字符串模板,让书籍的字符串表示更规范。
运行修正后的代码,断言会成功通过,实现按作者忽略大小写精确匹配并返回对应书籍列表的需求。
内容的提问来源于stack exchange,提问作者user20250841
相关产品推荐
相关产品推荐

