springle springle - 1 year ago 83
Python Question

Why doesn't this __repr__ function return a string?

class Person:
greeting = 'Hello'
def __repr__(self):
return self.greeting

>>> Sam = Person()
>>> Sam.greeting
>>> Sam

I am having difficulty understanding why the __repr__ function returns self.greeting without quotes. Any help is greatly appreciated.

Answer Source

The REPL outputs the repr of the object.

If you say

>>> 'Hello'

The repr of "Hello" is displayed, which is "'Hello'"

Since you are returning Hello rather than 'Hello' - that is what is displayed in the REPL

If you want the Person.repr to work like normal string repr, you can just call repr on self.greeting

>>> class Person:
...     greeting = 'Hello'
...     def __repr__(self):
...         return repr(self.greeting)
>>> Sam = Person()
>>> Sam
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download