擅长:python、mysql、java
<p>这背后的原因是python列表(在您的例子中是<code>a</code>)实现了<a href="http://docs.python.org/reference/datamodel.html#object.__iadd__" rel="noreferrer">^{<cd2>}</a>方法,该方法依次调用传递参数的<a href="http://docs.python.org/reference/datamodel.html#object.__iter__" rel="noreferrer">^{<cd3>}</a>方法。</p>
<p>下面的代码片段更好地说明了这一点:</p>
<pre><code>class MyDict(dict):
def __iter__(self):
print "__iter__ was called"
return super(MyDict, self).__iter__()
class MyList(list):
def __iadd__(self, other):
print "__iadd__ was called"
return super(MyList, self).__iadd__(other)
a = MyList(['a', 'b', 'c'])
b = MyDict((('d1', 1), ('d2', 2), ('d3', 3)))
a += b
print a
</code></pre>
<p>结果是:</p>
<pre><code>__iadd__ was called
__iter__ was called
['a', 'b', 'c', 'd2', 'd3', 'd1']
</code></pre>
<p>python解释器检查一个对象是否实现了<code>__iadd__</code>操作(<code>+=</code>),只有当它没有实现时,它才会通过在赋值之后执行add操作来模拟它。</p>