【问题标题】:How do I print out the attributes stored in an array instead of the objects?如何打印出存储在数组而不是对象中的属性?
【发布时间】:2020-10-05 22:25:16
【问题描述】:

如何打印出存储在数组中而不是对象中的章节名称的属性?

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 新手,所以我不确定实现这一目标的方法是什么,如果有人能帮助我,我将不胜感激!谢谢

【问题讨论】:

    标签: python arrays object printing instance


    【解决方案1】:

    您想要覆盖 __repr__ 而不是 __str__

    【讨论】:

    • 天哪!你是生命的救星!非常感谢
    • 我是否也可以像这样的数组一样访问它,因为它不是数组?打印(self.__chapters[1])
    • @Shee yep 试试看
    • 你太棒了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 2018-06-04
    • 2014-06-19
    • 1970-01-01
    相关资源
    最近更新 更多