【问题标题】:Why does + (plus) can concatenate two strings in Python?为什么+(加号)可以在Python中连接两个字符串?
【发布时间】:2016-04-10 03:36:45
【问题描述】:

我正在努力学习 Python。

w = "This is the left side of..."
e = "a string with a right side."
print w + e

解释为什么将两个字符串 w 和 e 与 + 相加会产生更长的字符串。

即使我知道它可以工作,但我不明白为什么以及如何?请帮帮我。

【问题讨论】:

  • 为什么这比+ 可以添加两个数字更让您感到惊讶?这就是 Guido 定义 Python 的 + 运算符的方式。
  • 解释为什么将两个字符串 w 和 e 与 + 相加会得到更长的字符串。 - 你还能期待什么?
  • 等你到'Hello' * 3

标签: python string python-internals


【解决方案1】:

+、-、* 和其他运算符将处理任何实现正确方法的东西。由于字符串实现了__add__(self, other)方法,你可以用+添加两个字符串。

试试这个:定义你自己的字符串子类并覆盖它的__add__方法:

class BadString(str):
    def __add__(self, other):
        # Ignore both input strings and just return this:
        return "Nothing Useful"

s = BadString("hello")

print("hello" + " world")    # "hello world"
print(s + "world")           # "Nothing Useful"

同样的技术,运算符重载,让您可以创建可以有效使用内置运算符(如 + 或 *)的类,就像可以相加的向量一样。

【讨论】:

    【解决方案2】:

    当您以这种方式添加(连接)两个字符串时,将调用类str 的__add__ 方法。 __add__ 方法就是这样工作的,但以下不是源代码中的逐字记录:

    def __add__(self, str1, str2):
        str3 = [str1] #Convert to list
        str3.append(str2) #Add the second string to the list
        return ''.join(str3) #Return the two joined
    

    例子:

    class MyString:
        def __init__(self, initstr):
            self.string = initstr
        def __add__(str1, str2):
            str3 = [str1.string] #Convert to list
            str3.append(str2.string) #Add the second string to the list
            return MyString(''.join(str3)) #Return the two joined
    

    >>> a = MyString("Hello")
    >>> b = MyString(" World!")
    >>> c = a+b
    >>> c.string
    'Hello World!'
    >>> 
    

    【讨论】:

      【解决方案3】:

      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) &amp;&amp; PyUnicode_CheckExact(right)(或 Python 2 中的 PyString_CheckExact(v) &amp;&amp; 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'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-08
        • 1970-01-01
        • 2021-03-16
        • 2014-05-27
        • 2017-03-11
        • 2017-07-22
        • 1970-01-01
        相关资源
        最近更新 更多