Определить метод __str__
.
>>> class Spam(object):
... def __str__(self):
... """my custom string representation"""
... return 'spam, spam, spam and eggs'
...
>>> x = Spam()
>>> x
<__main__.Spam object at 0x1519bd0>
>>> print x
spam, spam, spam and eggs
>>> print "The item is:" + str(x) + "."
The item is:spam, spam, spam and eggs.
>>> print "The item is: {}".format(x)
The item is: spam, spam, spam and eggs
edit: Демонстрация того, почему вы, вероятно, не хотите использовать __repr__
, например, для переопределения представленияВаш товар в списке или другом контейнере:
>>> class mystr(str):
... def __repr__(self):
... return str(self)
...
>>> x = ['this list ', 'contains', '3 elements']
>>> print x
['this list ', 'contains', '3 elements']
>>> x = [mystr('this list, also'), mystr('contains'), mystr('3 elements')]
>>> print x
[this list, also, contains, 3 elements]