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