equivalent to Java's toString()?
Roy Smith
roy at panix.com
Mon Apr 19 12:05:13 EDT 2004
In article <1087t9hc5vl833b at corp.supernews.com>,
"Michael Geary" <Mike at DeleteThis.Geary.com> wrote:
> Gabriel Cooper wrote:
> > What is the python equivalent to java's toString()?
> >
> > When debugging I want to be able to basically be able to do this:
> >
> > print MyObjectInstance
> >
> > or
> > print str(MyObjectInstance)
> >
> > and have it print out formatted output along the lines of:
> >
> > Object properties: Red=0 Yellow=0 Blue=255
>
> Define a __str__ method in your class. It works just like toString() in Java
> and JavaScript:
>
> >>> class MyTest( object ):
> ... def __str__( self ):
> ... return 'My Test!'
> ...
> >>> test = MyTest()
> >>> print test
> My Test!
> >>>
>
> Also see __repr__ for a related method.
>
> -Mike
Also, you might want to look at the pprint module. It's not quite what
you were asking for, but it's worth knowing about if you're doing this
kind of stuff.
More information about the Python-list
mailing list