简体   繁体   English

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

[英]How do I print out the attributes stored in an array instead of the objects?

How do I print out the attribute of chaptername stored in an array instead of it's object?如何打印出存储在数组中的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() 

I'm new to python so I'm not sure what is the way to achieve this and I would really appreciate if someone could help me out!我是python的新手,所以我不确定实现这一目标的方法是什么,如果有人能帮助我,我将不胜感激! Thank you谢谢

您想覆盖__repr__而不是__str__

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM