更新时间:2022-04-18 22:37:13
Python区分+
和+=
运算符,并为它们提供了单独的钩子. __add__
和
Python distinguishes between the +
and +=
operators and provides separate hooks for these; __add__
and __iadd__
. The list()
type simply provides a different implementation for the latter.
列表单独实现这些方法更有效; __add__
必须返回一个全新的列表,而__iadd__
可以仅扩展self
然后返回self
.
It is more efficient for lists to implement these separately; __add__
has to return a completely new list, while __iadd__
can just extend self
then return self
.
在C代码中,__iadd__
由 list_inplace_concat()
,它简单地调用listextend()
,或者在python代码中调用[].extend()
.后者根据设计采用 any 序列.
In the C code, __iadd__
is implemented by list_inplace_concat()
, which simply calls listextend()
, or, in python code, [].extend()
. The latter takes any sequence, by design.
The __add__
method on the other hand, represented in C by list_concat
, only takes a list
as input, probably for efficiency's sake; it can loop directly over the internal C array and copy items over to the new list.
最后,__iadd__
接受任何序列的原因是因为 PEP 203 (增强添加提案)已实现,对于列表而言,仅重用.extend()
方法是最简单的.
In conclusion, the reason __iadd__
accepts any sequence is because when PEP 203 (the Augmented Add proposal) was implemented, for lists it was simplest just to reuse the .extend()
method.