toString()

andres at corrada.com andres at corrada.com
Wed Jun 7 22:28:25 EDT 2000


On Wed, Jun 07, 2000 at 08:26:42PM -0500, David Allen wrote:
> 
> 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"?
> 

Yes, in Python it's called __str__.

> 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?
> 
> Thanks,

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

class Spam:
  .
  .
  .
  def __str__( self ):
     return self.someAttribute
     
------------------------------------------------------
Andres Corrada-Emmanuel   Email: andres at corrada.com
------------------------------------------------------




More information about the Python-list mailing list