2012-03-21 17 views
1

でクラスのメソッドをレンダリングする文字列を設定するには:どのように私が行う場合はPythonの

print "The item is:" + str(1) + "." 

私が取得します:

The item is 1. 

をしかし、私は私のクラスのオブジェクトを使用する場合、dbref(ここではX

print "The item is:" + str(x) + "." 

は私が取得します:

012それの1)、およびそれを文字列化しようとしています

私は自分のデザインの文字列を返すでしょう。クラス内で定義できる関数はありますか?

答えて

2

the __str__() methodから文字列を返します。同様に:

class SomeClass(object): 

    def __init__(self, value): 
    self.value = value 

    def __str__(self): 
    return '<SomeClass %s>' % self.value 
+0

これはリストにネストされるまで機能します。アイテムがリストの中にあるとき、そのリストが印刷されるときに同じ表現が与えられることを確実にする方法はありますか? – Kelketek

+2

あなたは実際にそれを望んでいませんが、 '__repr __()'はオブジェクトの表現を制御します。 –

+0

list comprehensionを使用してください:あなたの不変の 'eval(x .__ repr __())== x'を維持できると思わない限り、 – wim

1

__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] 
関連する問題