class Person:
greeting = 'Hello'
def __repr__(self):
return self.greeting
>>> Sam = Person()
>>> Sam.greeting
'Hello'
>>> Sam
Hello
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
'Hello'