I only changed self._hiddenlist into self when formatting; it'll output a recursion error. What does it actually mean and why? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I only changed self._hiddenlist into self when formatting; it'll output a recursion error. What does it actually mean and why?

class Queue: def __init__(self, contents): self._hiddenlist = list(contents) def push(self, value): self._hiddenlist.insert(0, value) def pop(self): return self._hiddenlist.pop(-1) def __repr__(self): return "Queue({})".format(self) queue = Queue([1, 2, 3]) print(queue) queue.push(0) print(queue) queue.pop() print(queue) print(queue._hiddenlist)

29th Jul 2018, 2:19 AM
Daniel Yang
Daniel  Yang - avatar
7 Answers
+ 2
It gives a recursion error because when you use a non-string object as a format parameter, Python will automatically call __repr__ on the object. The thing is, in your __repr__, Python keeps having to call __repr__ to get the string representation until the recursion depth limit is reached. EDIT: Essentially, the __repr__() definition boils down to: return "Queue({})".format("Queue({})".format("Queue({})".format("Queue({})"...
29th Jul 2018, 3:56 AM
LunarCoffee
LunarCoffee - avatar
+ 7
LunarCoffee you're saying if there's no __str__ magic method added python calls the repr function (which is called when the object as an arg in the print function) to get the string representation. Is that right?
29th Jul 2018, 4:01 AM
Yash✳️
Yash✳️ - avatar
+ 2
In your __repr__() function you put self as the parameter for format(), instead of self._hiddenlist.
29th Jul 2018, 3:26 AM
LunarCoffee
LunarCoffee - avatar
+ 2
yash When __repr__() is defined but __str__() is not, Python behaves as if __str__ = __repr__.
29th Jul 2018, 4:07 AM
LunarCoffee
LunarCoffee - avatar
+ 1
Yes, I'm aware of that😅 I was changing up stuff to test things out I was asking: what does it even mean if I am to do this?
29th Jul 2018, 3:32 AM
Daniel Yang
Daniel  Yang - avatar
+ 1
Awesome. Thanks guys💪
29th Jul 2018, 5:16 AM
Daniel Yang
Daniel  Yang - avatar
0
So __repr__() can take the place of __str__() if there's not one? What else can it take the place of?
29th Jul 2018, 5:21 AM
Daniel Yang
Daniel  Yang - avatar