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

如何保留FictionBook类__str__方法同时完整存储对象所有属性?

问题解答

原始代码

class Amazon:
    def __init__(self):
        self.bestsellers = []
    def read_books_csv(self, path):
        with open(path, encoding='utf-8-sig') as csvfile:
            spam = csv.reader(csvfile)
            iterator = iter(spam)
            next(iterator)
            for x in spam:
                if x[6] == 'Fiction':
                    print(x)
                    self.bestsellers.append(FictionBook(*x[0:7]))
class FictionBook(Book):
    def __init__(self, title, author, rating, reviews, price, year, genre):
        super().__init__(title, author, rating, reviews, price, year, genre)
    def __str__(self):
        return f"{self.title} : {self.genre} {self.year[0]}"

问题描述

我的FictionBook类的__str__方法必须保持现有输出格式(返回title、genre、year相关内容),但需要在Amazon类的bestsellers列表中存储包含title、author、rating、reviews、price、year、genre全部属性的FictionBook对象。我误以为当前仅存储了三个属性,请问该如何处理?


解答

你当前的代码已经完整存储了所有7个属性,不需要做任何修改,误解的根源在于__str__方法只展示了3个属性,但对象本身的所有属性都被正常保存了:

  • FictionBook的构造函数接收了全部7个参数,并且通过super().__init__将这些参数传递给父类Book的构造函数(只要Book类的构造函数是常规实现,会将这7个参数存储为实例属性)。
  • 在Amazon类的read_books_csv方法中,你通过FictionBook(*x[0:7])把CSV里的7列数据全部传给了FictionBook的构造函数,每个实例都会完整包含title、author、rating、reviews、price、year、genre这7个属性。
  • __str__方法仅仅是控制对象被打印时的显示内容,不会影响对象实际存储的属性。你可以随时通过book.author、book.rating、book.price这样的方式访问其他属性,不受__str__的限制。

验证方法

如果想确认属性是否完整存储,可以添加一段测试代码:

# 假设已经实例化Amazon并调用了read_books_csv方法
amazon = Amazon()
amazon.read_books_csv("your_books.csv")

for book in amazon.bestsellers:
    print(f"书名:{book.title},作者:{book.author},评分:{book.rating},价格:{book.price}")

执行后就能看到所有属性都能正常访问。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:30:41