Python 使用+ 连接字符串,因为这是 Python 的核心开发人员定义该运算符的方式。
虽然__add__ 特殊方法通常用于实现+ 运算符,但+ (BINARY_ADD bytecode instruction) 确实不 调用str.__add__,因为+ 处理字符串特别是在 Python 2 和 Python 3 中。如果+ 的两个操作数都是字符串,Python 会直接调用字符串连接函数,从而无需调用特殊方法。
Python 3 调用unicode_concatenate (source code):
TARGET(BINARY_ADD) {
PyObject *right = POP();
PyObject *left = TOP();
PyObject *sum;
if (PyUnicode_CheckExact(left) &&
PyUnicode_CheckExact(right)) {
sum = unicode_concatenate(left, right, f, next_instr);
/* unicode_concatenate consumed the ref to v */
}
else {
sum = PyNumber_Add(left, right);
Py_DECREF(left);
}
...
Python 2 调用string_concatenate (source code):
case BINARY_ADD:
w = POP();
v = TOP();
if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
/* INLINE: int + int */
register long a, b, i;
a = PyInt_AS_LONG(v);
b = PyInt_AS_LONG(w);
/* cast to avoid undefined behaviour
on overflow */
i = (long)((unsigned long)a + b);
if ((i^a) < 0 && (i^b) < 0)
goto slow_add;
x = PyInt_FromLong(i);
}
else if (PyString_CheckExact(v) &&
PyString_CheckExact(w)) {
x = string_concatenate(v, w, f, next_instr);
/* string_concatenate consumed the ref to v */
goto skip_decref_vx;
}
else {
slow_add:
x = PyNumber_Add(v, w);
...
这种优化自 2004 年以来一直在 Python 中。来自issue980695:
...在附加的补丁中 ceval.c 两个字符串的特殊情况相加(与两个整数相加的特殊情况相同)
但请注意,主要目标不仅仅是消除特殊属性查找。
不管怎样,str.__add__ 仍然按预期工作:
>>> w.__add__(e)
'This is the left side of...a string with a right side.'
并且 Python 将调用 str 的子类的 __add__ 方法,因为上面代码 sn-ps 中的 PyUnicode_CheckExact(left) && PyUnicode_CheckExact(right)(或 Python 2 中的 PyString_CheckExact(v) && PyString_CheckExact(w))将为 false:
>>> class STR(str):
... def __add__(self, other):
... print('calling __add__')
... return super().__add__(other)
...
>>> STR('abc') + STR('def')
calling __add__
'abcdef'