equivalent to Java's toString()?

G

Gabriel Cooper

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

currently I get something like this:

<Some Object at 0xff32ffca3>

In java it would look like this:

class SomeClass {
[...]
String toString() {
return new String("Object properties: Red=" + red + " Yellow: " +
yellow + " Blue: " + blue);
}
}
 
M

Michael Geary

Gabriel said:
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:
.... def __str__( self ):
.... return 'My Test!'
....
Also see __repr__ for a related method.

-Mike
 
R

Roy Smith

"Michael Geary said:
Define a __str__ method in your class. It works just like toString() in Java
and JavaScript:

... def __str__( self ):
... return '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.
 
Y

Ype Kingma

Michael said:
Define a __str__ method in your class. It works just like toString() in Java
and JavaScript:

... def __str__( self ):
... return 'My Test!'
...

Also see __repr__ for a related method.

-Mike

Closing the circle, just for info, from the java docs of jython:

http://www.jython.org/docs/javadoc/org/python/core/PyObject.html#__str__()

"""Equivalent to the standard Python __str__ method. This method should not
typically need to be overridden. The easiest way to configure the string
representation of a PyObject is to override the standard Java toString
method."""

Regards,
Ype
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top