+ 2

can anyone shed some more light on the magic method __repr__ pls

__repr__

22nd Oct 2016, 12:07 PM
Paul Obasi
Paul Obasi - avatar
4 Answers
+ 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.
22nd Oct 2016, 2:32 PM
Zen
Zen - avatar
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
31st Dec 2016, 12:05 AM
Simon
- 5
Khan gufra
26th Oct 2016, 11:48 AM
gufrankhan
gufrankhan - avatar
- 5
Pathan I m Salman Khan
26th Oct 2016, 11:48 AM
gufrankhan
gufrankhan - avatar