Why does str not have a __radd__ method?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Aug 13 12:00:09 EDT 2014
I just tried to override str.__radd__:
class Special(str):
def __radd__(self, other):
print("I'm special!")
return super().__radd__(self, other)
My __radd__ method was called correctly by the + operator, but to my
surprise, the super().__radd__ call failed with:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __radd__
AttributeError: 'super' object has no attribute '__radd__'
Sure enough, in both Python 3.3 and 2.7:
py> str.__radd__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'str' has no attribute '__radd__'
This is especially astonishing, since int and float both have __radd__
methods, and yet numeric addition is commutative (x+y == y+x) whereas the
same is not true for string concatenation.
What is the rationale for str not having __radd__ method?
--
Steven
More information about the Python-list
mailing list