如何为Python的Book类实现指定格式的description()输出?
修正后的Book类实现
以下是满足需求的完整代码,同时包含所有测试场景的验证:
class Book: def __init__(self, title, author, price, no_pages=None, year=None): self.title = title self.author = author self.price = price self.no_pages = no_pages self.year = year def description(self): # 初始化必填字段的描述行 desc_lines = [ f"Title: {self.title}", f"Author: {self.author}", f"Price: £{self.price}" ] # 仅当年份参数存在时添加对应行 if self.year is not None: desc_lines.append(f"Year Published: {self.year}") # 仅当页数参数存在时添加对应行 if self.no_pages is not None: desc_lines.append(f"No. of Pages: {self.no_pages}") # 将所有行拼接为多行字符串返回 return '\n'.join(desc_lines) if __name__ == "__main__": # 测试场景1:仅必填参数 book1 = Book("1984", "George Orwell", 6.99) print(book1.description()) print("---") # 测试场景2:添加页数参数 book2 = Book("1984", "George Orwell", 6.99, no_pages=328) print(book2.description()) print("---") # 测试场景3:添加年份参数 book3 = Book("1984", "George Orwell", 6.99, year=1949) print(book3.description()) print("---") # 测试场景4:同时添加页数和年份参数 book4 = Book("1984", "George Orwell", 6.99, no_pages=328, year=1949) print(book4.description())
关键修改说明
- 输出逻辑调整:原方法直接打印内容且无返回值,导致调用
print(book.description())时会额外输出None。改为构建字符串列表并拼接为多行字符串返回,完全匹配示例中的输出要求。 - 可选字段条件输出:通过判断参数是否为
None,仅在参数存在时添加对应描述行,避免输出空值的无效内容。 - 格式修正:将年份的输出标签从
Year改为Year Published,与示例指定格式一致。 - 测试覆盖:在主函数中添加了所有测试场景,方便快速验证代码是否符合要求。
内容的提问来源于stack exchange,提问作者Mir Ahmed Abbas Khan
相关产品推荐
相关产品推荐

