[Tutor] method to print in interpreter

Bruce Sass bsass@freenet.edmonton.ab.ca
Sun, 24 Jun 2001 15:42:34 -0600 (MDT)


On Fri, 22 Jun 2001, Allan Crooks wrote:
> > I would like ">>> p" to return something like '(1,2)', too.
>
> Whenever you "print" an object, it will use the string returned by the str function.
> Whenever you have an object that is displayed without using print, it uses the repr function.
>
> So in your Point class, you could add this line:
>
> def __repr__(self):
>   return str(self)
>
> Which returns the same string as when you print it.

...or you can do...

	def __str__(self):
	    return ...

	__repr__ = __str__

...and save on a def, but you probably really want...

	def __str__(self):
	    return ...

	def __repr__(self):
	    return "Point(" + repr(x) + ", " + repr(y) + ")"

...so you can do...

	a = Point(1,2)
	b = eval(repr(a))

...and have it work as you would expect (i.e., b == Point(1,2)).


- Bruce