且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

列表扩展了奇怪的行为

更新时间: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.

另一方面,在C中由

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.