Question
In the context of this exercise, can the LinkedList
class impelement the __str__()
method to make it possible to print a list object?
Answer
Yes, any class may implement __str__()
or __repr__()
to directly print a representation of the object. Since the LinkedList
class already has a method stringify_list()
to convert the list contents to a string, an implementation of __str__()
could easily call this method as shown in the code snippet below.
class LinkedList:
def __str__(self):
return self.stringify_list()
This would allow for the list object to be printed as shown in this example.
mylist = LinkedList()
mylist.insert_beginning(1)
mylist.insert_beginning(2)
mylist.insert_beginning(3)
print(mylist)
#OUTPUTS:
#3
#2
#1