confused about __str__ vs. __repr__

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Dec 18 19:11:27 EST 2008


En Thu, 18 Dec 2008 14:05:32 -0200, Mikael Olofsson <mikael at isy.liu.se>
escribió:

> Diez B. Roggisch wrote:
>> Yep. And it's easy enough if you don't care about them being different..
>>  def __repr__(self):
>>     return str(self)
>
> If I ever wanted __str__ and __repr__ to return the same thing, I would  
> make them equal:
>
> def __str__(self):
>      return 'whatever you want'
> __repr__ = __str__
>
> That makes it more obvious to me what's going on. As a bonus, it saves  
> one method call for every repr call.

It's even easier to define only __repr__, __str__ defaults to it:

>>> class OnlyRepr(object):
...   def __repr__(self): return "repr called"
...
>>> class OnlyStr(object):
...   def __str__(self): return "str called"
...
>>> class Both(OnlyRepr, OnlyStr):
...   pass
...
>>> r = OnlyRepr()
>>> s = OnlyStr()
>>> b = Both()
>>> print "only repr:", repr(r), str(r)
only repr: repr called repr called
>>> print "only str: ", repr(s), str(s)
only str:  <__main__.OnlyStr object at 0x00BA10F0> str called
>>> print "both:     ", repr(b), str(b)
both:      repr called str called

-- 
Gabriel Genellina




More information about the Python-list mailing list