擅长:python、mysql、java
<p>这行代码是一种将<code>obj</code>转换成字符串的方法,方法是调用<strong>基类型<code>object</code></strong>的默认<code>__str__</code>方法,该方法生成一个包含类名和内存中实例地址的字符串,例如<code><Kangaroo instance at 0xAABBCC></code>。你知道吗</p>
<p>通常,人们会使用<code>str(obj)</code>,但在这种情况下,如果<code>obj</code>是另一个<code>Kangaroo</code>,那么<code>Kangaroo</code>中定义的相同<code>__str__()</code>方法将被递归调用,从而导致生成类似这样的内容:</p>
<pre><code>foo = Kangaroo('foo')
bar = Kangaroo('bar')
baz = Kangaroo('baz')
baz.put_in_pouch(1)
bar.put_in_pouch(baz)
foo.put_in_pouch(bar)
# Result of print str(foo)
foo has pouch contents:
bar has pouch contents:
baz has pouch contents:
1
</code></pre>
<p>相反,使用<code>object.__str__()</code>可以避免递归调用该方法,并给出:</p>
<pre><code># Result of print str(foo)
foo has pouch contents:
<__main__.Kangaroo instance at 0x7fc3a864d128>
</code></pre>