[Tutor] How to call a method with a print statement?

Kent Johnson kent37 at tds.net
Thu Nov 12 13:00:41 CET 2009


On Thu, Nov 12, 2009 at 6:35 AM, Luke Paireepinart
<rabidpoobear at gmail.com> wrote:
>
>
> On Thu, Nov 12, 2009 at 5:29 AM, Jeff R. Allen <jra at nella.org> wrote:
>>
>> You are looking for the __str__ method. See
>> http://docs.python.org/reference/datamodel.html#object.__str__
>>
> Can't you also implement __repr__?

Yes, in fact if you are only going to implement one of __str__ and
__repr__, arguably __repr__ is a better choice. __repr__() is called
by the interactive interpreter when it displays an object. __str__ is
called by print, and if you don't define __str__ it will call
__repr__. So defining only __str__ will not give a custom
representation unless you print:

In [1]: class Foo():
   ...:     def __str__(self):
   ...:         return "I'm a Foo"

In [2]: f = Foo()

In [3]: f
Out[3]: <__main__.Foo instance at 0x1433468>

In [4]: print f
I'm a Foo


Defining __repr__ will give the custom representation when you just
give the name of the object:

In [5]: class Foo2():
   ...:     def __repr__(self):
   ...:         return "I'm a Foo2"
   ...:
   ...:

In [6]: f2=Foo2()

In [7]: f2
Out[7]: I'm a Foo2

In [8]: print f2
I'm a Foo2

Kent


More information about the Tutor mailing list