0
What is __repr__ ??
What is the use of magic method __repr__ in oop.
5 Answers
+ 1
Seb TheS ofcourse
+ 1
class A:
#Using default constructor.
def __repr__(self):
print("Hello")
return "90" #Return value must be a string.
a = A()
b = repr(a)
#Output: Hello
print(b)
#Output: 90
+ 1
#There is actually a nice usage for __repr__, because the print function often calls this, when you print the object.
class Vectors:
def __init__(self, i, j):
self.i = i
self.j = j
def __repr__(self):
return "{0}i + {1}j".format(self.i, self.j)
a = Vector(5, 7)
print(a)
#Output: 5i + 7j
0
Would you want an example?
- 2
It will be called as a function, when you use an object of the class as an argument to the repr builtin function.