0

Can somebody please help me why the __repr__ method is called with the q.pop() method in the code below?

>>> class Item:
...     def __init__(self, name):
...         self.name = name
...     def __repr__(self):
...         return 'Item({!r})'.format(self.name)
...
>>> q = PriorityQueue()
>>> q.push(Item('foo'), 1)
>>> q.push(Item('bar'), 5)
>>> q.push(Item('spam'), 4)
>>> q.push(Item('grok'), 1)
>>> q.pop()
Item('bar')
>>> q.pop()
Item('spam')
>>> q.pop()
Item('foo')
>>> q.pop()
Item('grok') 
>>>
pointerless
  • 753
  • 9
  • 20
hk_03
  • 192
  • 3
  • 12

1 Answers1

3

The built-in __repr__ function is used to return a printable format of an object. In this case, because Item is a custom object/class, the override in __repr__ allows an instance of the Item to be displayed in the terminal. See when they call q.pop(), the item is printed to the screen, and this printing is done through the override of the __repr__ function.

q.pop() prints Item('bar')because the overridden __repr__ function for Item says to print 'Item({!r})'.format(self.name). This prints the word: Item('') and the format part fills in the actual contents of the item between the single quotes, thus resulting in Item('bar') being printed to the screen.

Read more about this here: Purpose of Python's __repr__

Felix Guo
  • 2,700
  • 14
  • 20
  • Thank you for your answer! I read about __repr__ here before, but the thing that i can't see is where is exactly the explicit call for the __repr__ function. I mean if it would be a __del__ i could understand the explicit call because with the pop the object will be deleted. But the exact question is where the __repr__ is called through the pop()? – hk_03 Jul 27 '17 at 23:07
  • 1
    The `pop()` function returns an `Item`. When you call a function in python's `REPL` mode (that's when you run `python` in the terminal), any function's return value is printed to the screen. When the return value is printed, Python automatically calls `__repr__` to convert the object to a string that can be displayed to the user. This is the result that is shown on the screen. There is no explicit call to `__repr__`, but rather is a result of the python `REPL` evaluator. – Felix Guo Jul 27 '17 at 23:24