Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this __repr__ function return a string?

Tags:

python

repr

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.

like image 664
springle Avatar asked Mar 17 '26 09:03

springle


1 Answers

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'
like image 55
John La Rooy Avatar answered Mar 18 '26 21:03

John La Rooy