How do I print out the attribute of chaptername stored in an array instead of it's object?
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! Thank you
You want to override __repr__
instead of __str__
.