[Tutor] overloading object for printing?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Aug 20 21:59:32 CEST 2004



On Sat, 14 Aug 2004, Joe Music wrote:

> Is there some equivalent in Python to the to_s() method in Java which a
> class can overload in order to customize the output of an object?
> Thanks.


Hi Joe,


Yes, there is a builtin function called str() that takes anything, and
returns a string representation.  In Python, str() works on everything,
since all things are objects, even "primitive" things like integers:

###
>>> str(42)
'42'
>>> str([1, 2, 3])
'[1, 2, 3]'
>>> class Foo:
...     pass
...
>>> f = Foo()
>>> str(f)
'<__main__.Foo instance at 0x402d382c>'
###


Classes that define an __str__() method can customize the way that they
react to str():

###
>>> class Bar:
...     def __str__(self):
...         return "Bar bar!"
...
>>> b = Bar()
>>> str(b)
'Bar bar!'
###


See:

    http://www.python.org/doc/ref/specialnames.html

for a complete list of "special" method names that allow us to hook
Python-specific behavior into our classes.


Good luck to you!



More information about the Tutor mailing list