+ 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.
6 Respuestas
+ 4
__repr__ is a method of your object.
You call it by obj.__repr__
+ 1
Benjamin Jürgens why does not obj.__repr__ does a type check ??
However if it does then both print statements will give error.
+ 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
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__()
0
Frogged in line 7 if we replaced str with repr then also the code will work..how ??