toString()

Quinn Dunkan quinn at xeno.ugcs.caltech.edu
Thu Jun 8 19:58:56 EDT 2000


On Wed, 07 Jun 2000 20:26:42 -0500, David Allen <s2mdalle at titan.vcu.edu> wrote:
>Sorry if this is a FAQ - I can't seem to find the answer anywhere.
>
>Is there such thing as a toString() for objects like java has that
>will be automatically called when an object is used "as a string"?
>
>I.e. when you create an object, __init__ gets called automatically,
>so if I say:
>
>x = Spam()
>print x
>
>can I put a method in Spam such that it will print out something
>useful based off of the class fields rather than the ugly data 
>definition?

Yes, it's __str__  See the Language Reference 3.3 "Special method names" for
all the double-underscore magic you can accomplish.



More information about the Python-list mailing list