faqts : Computers : Programming : Languages : Python : Common Problems : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 5 people (100%) answered Yes
Recently 4 of 4 people (100%) answered Yes

Entry

Is there such a thing as a toString() for objects, like java has, that will be automatically called when an object is used "as a string"?

Jun 9th, 2000 00:31
unknown unknown, Andres Corrada-Emmanuel, Quinn Dunkan


Problem:

ie. 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 on the class fields rather than the ugly data definition?

Solution:

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

In your class definition for Spam include a __str__ method, something 
like the following:

class Spam:
  .
  .
  .
  def __str__( self ):
     return self.someAttribute