springle springle - 9 days ago 6x
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.


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