+ 2
can anyone shed some more light on the magic method __repr__ pls
__repr__
4 ответов
+ 9
The __repr__ method affects how the object is represented when you try to print it.
Example:
class Complex:
def __init__(self, re, im):
self.re = re
self.im = im
def __repr__(self):
return "({} + {}i)".format(self.re, self.im)
c1 = Complex(2, 3)
print(c1)
Try removing the __repr__ of the example to see the difference.
0
the print output for this, with the __repr__ is
(2 + 3i)
without the __repr__ it produces an error because there are no methods etc to print
simply put, __repr__ allows you to create/format "how" you want the print() function to display your class's output.
so, from the above example
....
def __repr__(self):
return "({} + {}i)".format(self.re, self.im)
prints
(2 + 3i)
if you change it to
....
def __repr__(self):
return "{} plus {}".format(self.re, self.im)
it will print
2 plus 3
instead.
I hope this has made it clearer for you
- 5
Khan gufra
- 5
Pathan I m Salman Khan