<p>使用<code>__str__</code>方法的目的是创建对象的字符串表示形式。<code>__str__</code><em>应该返回字符串。如果<code>__str__</code>的实现代替<em>打印</em>字符串表示,而不返回任何内容,则当对象在字符串上下文中使用时,将引发<code>TypeError</code>。例如:</p>
<pre><code>def __str__(self):
print '%f/%f'%(self.num,self.den)
</code></pre>
<p>如果我们要显示这样的分数对象:</p>
<pre><code>f = Fraction(1,2)
print f
</code></pre>
<p>我们有个例外:</p>
<pre><code>Traceback (most recent call last):
File "/Users/.../Desktop/...", line 13, in <module>
print f
TypeError: __str__ returned non-string (type NoneType)
>>>
</code></pre>
<p>这是因为<code>__str__</code>用于获取对象的字符串表示,而不是打印它(按照约定,只要返回字符串,就可以打印)。这就是<code>print</code>语句/函数与<code>__str__</code>方法一起使用的功能。</p>
<p>另一方面,像<code>show</code>这样的方法:</p>
<pre><code>def show(self):
print(self.num,"/",self.den) #or even print(self) (for the last part of answer)
</code></pre>
<p>在上述情况下基本上等同于<code>print(f)</code>(除了它包含操作数旁边的空格)。<code>show</code>用于<em>输出</em>字符串表示,而<code>__str__</code>用于<em>获取</em>表示。</p>
<p>但是,可以将附加逻辑添加到<code>show</code>中,这在构造字符串表示时是不适当/不必要的,因此使用这两种方法是有意义的。</p>
<p>但是,您可以使用像<code>show</code>这样的方法,其中<code>print</code>语句不合适,即:</p>
<pre><code>if f.show(): pass
if print(f): pass #raise exception
</code></pre>