I'm learning Learn Python the hard way.
w = "This is the left side of..."
e = "a string with a right side."
print w + e
Explain why adding the two strings w
and e
with + makes a longer string.
Even I know it can work, but I don't understand why and how? Please help me.
The
__add__
method of the classstr
is called when you add (concatenate) two strings in this manner. The__add__
method works as such, but the following is not verbatim from the source code:Example:
Python uses
+
to concatenate strings because that's how core developers of Python defined that operator.While it's true that
__add__
special method is normally used to implement the+
operator,+
(BINARY_ADD
bytecode instruction) does not callstr.__add__
because+
treats strings specially in both Python 2 and Python 3. Python invokes the string concatenation function directly if both operands of+
are strings, thus eliminating the need to call special methods.Python 3 calls
unicode_concatenate
(source code):Python 2 calls
string_concatenate
(source code):This optimization has been in Python ever since 2004. From the issue980695:
But note that the main goal was greater than elimination of special attribute lookup.
For what it's worth,
str.__add__
still works as expected:and Python will call
__add__
methods of subclasses ofstr
, becausePyUnicode_CheckExact(left) && PyUnicode_CheckExact(right)
(orPyString_CheckExact(v) && PyString_CheckExact(w)
, in Python 2) from the code snippets above will be false:+
,-
,*
, and other operators will work on anything that implements the right methods. Since strings implement the__add__(self, other)
method, you can add two strings with+
.Try this: define your own string subclass and override its
__add__
method:The same technique, operator overloading, lets you create classes that can use the built-in operators like
+
or*
usefully, like vectors that can be added together.