列表扩展了奇怪的行为 [英] List extending strange behaviour
问题描述
在Python(2.7)中发现了从未有过的有趣的东西.
Found interesting thing in Python (2.7) that never mentioned before.
此:
a = []
a += "a"
有效,结果是:
>>> a
>>> ["a"]
但是
a = []
a = a + "a"
给予
>>> TypeError: can only concatenate list (not "str") to list
有人可以解释为什么吗?感谢您的回答.
Can someone explain why? Thanks for your answers.
推荐答案
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.
这篇关于列表扩展了奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!