__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
編集:
:あなたはおそらく、リストまたは他の容器にあなたの商品の過剰乗っ表現に、たとえば、__repr__
を使用したくない理由の Demonsration
>>> 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]
出典
2012-03-21 06:24:27
wim
これはリストにネストされるまで機能します。アイテムがリストの中にあるとき、そのリストが印刷されるときに同じ表現が与えられることを確実にする方法はありますか? – Kelketek
あなたは実際にそれを望んでいませんが、 '__repr __()'はオブジェクトの表現を制御します。 –
list comprehensionを使用してください:あなたの不変の 'eval(x .__ repr __())== x'を維持できると思わない限り、 – wim