0

Why __repr__ works and repr does not on a dictionary return?

class Person: name = "" age = 0

def __init__(self, personName, personAge):
    self.name = personName
    self.age = personAge

def __repr__(self):
    return {'name':self.name, 'age':self.age}

p = Person('Pankaj', 34)

print(p.__repr__())

print(repr(p))

OUTPUT:

{'name': 'Pankaj', 'age': 34}

Traceback (most recent call last):

...

print(repr(p))

TypeError: __repr__ returned non-string (type dict)

eric0109
  • 1
  • 1

1 Answers1

0

Reading the below I think option 2 returns an object, option 1 a string.

The official Python documentation says repr() is used to compute the “official” string representation of an object. The repr() built-in function uses repr() to display the object. repr() returns a printable representation of the object, one of the ways possible to create this object.

https://www.tutorialspoint.com/What-does-the-repr-function-do-in-Python-Object-Oriented-Programming

Does print call str or repr? str() displays today's date in a way that the user can understand the date and time. repr() prints “official” representation of a date-time object (means using the “official” string representation we can reconstruct the object).

https://www.geeksforgeeks.org/str-vs-repr-in-python/

Christian
  • 4,902
  • 4
  • 24
  • 42
  • In https://www.tutorialspoint.com/What-does-the-repr-function-do-in-Python-Object-Oriented-Programming, it says: "__repr__() is used to compute the “official” string representation of an object ... __repr__() returns a printable representation of the object" (1st para.) It seems not clear. – eric0109 May 10 '20 at 04:16
  • As "The repr() built-in function uses `__repr__()` to display the object." in the first quote, repr & `__repr__` should have same result. – eric0109 May 10 '20 at 04:19
  • Please check if this helps you: https://stackoverflow.com/questions/1984162/purpose-of-pythons-repr – Christian May 12 '20 at 22:16