[Tutor] Alter print action for objects
Jordan Greenberg
jordangreenberg at gmail.com
Wed Jul 23 13:22:00 CEST 2008
Shrutarshi Basu wrote:
> I'm working on a graph class to become more familiar with graphs in
> general. I'd like to be able to do something like 'print gr' and get
> something intelligible like a list of vertices. But using print on a
> Graph class instance simply returns <Graph instance at some_hex_addr>
> Is there someway I can change what print prints?
>
print will print the string returned by an object's __str__ method.
Try something like this:
In [1]: class Example(object):
...: def __init__(self, x):
...: self.x=x
...: def __str__(self):
...: return "x is: %s"%(self.x)
...:
In [3]: ex=Example(5)
In [4]: print ex
x is: 5
The "basic customization" page in the Python Reference Manual may be of
use as well: http://docs.python.org/ref/customization.html
HTH,
JordanG
More information about the Tutor
mailing list