python - Why is __repr__ called in the code below? -
can please me why __repr__ method called q.pop() method in 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') >>>
the built-in __repr__ function used return printable format of object. in case, because item custom object/class, override in __repr__ allows instance of item displayed in terminal. see when call q.pop(), item printed screen, , printing done through override of __repr__ function.
q.pop() prints item('bar')because overridden __repr__ function item says print 'item({!r})'.format(self.name). prints word: item('') , format part fills in actual contents of item between single quotes, resulting in item('bar') being printed screen.
read more here: purpose of python's __repr__
Comments
Post a Comment