+ 1

__repr__ is confusing me too much.

class myclass: def __init__(self): self.name="Raj" self.age=21 def __repr__(self): return {'name':self.name} obj=myclass() print(obj.__repr__())#prints without error print(repr(obj))# gives error saying __repr__ didnot returned a string. but print(obj.__repr__()) and print(repr(obj)) are exactly same. why the later one gives error where the former one gives no error.

9th Jun 2021, 8:08 AM
kushal
6 Réponses
+ 4
__repr__ is a method of your object. You call it by obj.__repr__
9th Jun 2021, 8:41 AM
Oma Falk
Oma Falk - avatar
9th Jun 2021, 9:05 AM
Oma Falk
Oma Falk - avatar
+ 1
Benjamin Jürgens why does not obj.__repr__ does a type check ?? However if it does then both print statements will give error.
9th Jun 2021, 11:14 AM
kushal
+ 1
kushal there is no type check in your code for __repr__, so it doesn't check. __repr__ is supposed to return a string, which is violated by your code. As you discovered that works fine as long as you use it as a normal method, due to print implicitly converting arguments to string. But repr is a separate method which calls __repr__ on its argument and checks the type. That's why it doesn't work if you don't return a string
9th Jun 2021, 12:19 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
0
Your __repr__ returns a dictionary repr(obj) is a call to a method and that merhod does a type check before returning obj.__repr__()
9th Jun 2021, 9:35 AM
Benjamin Jürgens
Benjamin Jürgens - avatar
0
Frogged in line 7 if we replaced str with repr then also the code will work..how ??
9th Jun 2021, 11:20 AM
kushal