<p>看看<code>str()</code>的<a href="https://docs.python.org/3/library/stdtypes.html#str" rel="nofollow noreferrer">docs</a>。相关部分:</p>
<blockquote>
<p><code>str(object)</code> returns <code>object.__str__()</code>, which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a <code>__str__()</code> method, then <code>str()</code> falls back to returning <code>repr(object)</code>.</p>
</blockquote>
<p>类似地,<code>repr()</code>调用<code>__repr__()</code>。你知道吗</p>
<p>从<a href="https://docs.python.org/3/library/functions.html#print" rel="nofollow noreferrer">docs</a>到<code>print()</code>:</p>
<blockquote>
<p>All non-keyword arguments are converted to strings like <code>str()</code> does and written to the stream</p>
</blockquote>
<p>因此<code>print(obj)</code>的行为类似于<code>str(obj)</code>,只是它写入流而不是返回值。这意味着你的解决方案比你想象的要简单:</p>
<pre class="lang-py prettyprint-override"><code># you can iterate over the list directly
for mac_auth in mac_list:
# sep='\n' is the default value, so you don't need to specify it
print(mac_auth)
</code></pre>
<hr/>
<p>作为旁注,你现在看到这个的原因是:</p>
<pre class="lang-py prettyprint-override"><code><bound method MacAuth.__str__ of XXXXXXXXXXXX>
</code></pre>
<p>因为方法<code>MacAuth.__str__</code>也是一个对象,定义了它自己的字符串表示,并且<code>print</code>将方法转换为字符串。你知道吗</p>
<p>绑定方法的表示包括对它们绑定到的对象的引用,在本例中是<code>MacAuth</code>对象。流程与此类似:</p>
<ol>
<li><code>print()</code>尝试将绑定到<code>MacAuth</code>对象的方法<code>__str__</code>(它本身就是一个对象)转换为字符串</li>
<li><code>__str__</code>的字符串表示包括它绑定到的对象,类似于<code><bound method MacAuth.__str__ of [MacAuth obj]></code></li>
<li>要打印<code>[MacAuth obj]</code>部分,将调用该对象的<code>__str__</code>,它根据需要返回<code>mac_address</code>属性</li>
</ol>