为了账号安全,请及时绑定邮箱和手机立即绑定

如何打印存储在数组中的属性而不是对象?

如何打印存储在数组中的属性而不是对象?

冉冉说 2023-10-06 18:49:08
如何打印存储在数组中而不是其对象中的 ChapterName 的属性?class Book:    def __init__(self):        self._chapters = []    def addchapter(self, chapter):        self._chapters.append(chapter)    def getchapters(self):        #How do I print out ["First", "Second", "Third"] instead?        print(self._chapters) #<- prints out [<__main__.Chapter object at 0x10b849c40>, <__main__.Chapter object at 0x10b8901f0>, <__main__.Chapter object at 0x10b890310>]class Chapter:    def __init__(self, chaptername):        self._chaptername = chaptername    def __str__(self):        return f"{self._chaptername}"b = Book()b.addchapter( Chapter("First") )b.addchapter( Chapter("Second") )b.addchapter( Chapter("Third") )b.getchapters() 我是 python 新手,所以我不确定实现此目标的方法是什么,如果有人可以帮助我,我将非常感激!谢谢
查看完整描述

1 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

您想要覆盖__repr__而不是__str__.



查看完整回答
反对 回复 2023-10-06
  • 1 回答
  • 0 关注
  • 49 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信