I've written the following two methods in a class:
def __repr__(self):
return 'REPR: %s' % self.__class__.__name__
def __str__(self):
return 'STR: %s' % self.__class__.__name__
And to see when they are called:
>>> print t
STR: TPR
>>> t
REPR: TPR
>>> str(t) #obvious
'STR: TPR'
>>> repr(t) #obvious
'REPR: TPR'
Is there a general rule of thumb as to which one is called when, for example, when printing a %s
or within a format string, etc. Or is it safe to assume that str
is always called if the obj is ever called in some sort of formatted string/unicode place?
Finally, if I ever wanted to "just use one", what would be a better way to do this?
def __repr__(self):
return __str__(self)
or:
def __str__(self):
return __repr__(self)
Or does it not matter?