equivalent to Java's toString()?
Ype Kingma
ykingma at accessforall.nl
Mon Apr 19 13:17:02 EDT 2004
Michael Geary 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
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
More information about the Python-list
mailing list