Why doesn't str have a __radd__ method in Python?

str has other methods like __rmod__, __rsub__, or __rmul __

int had __radd__ method

Strange, and I would like to know why.

An example of a radd beeing that is called the first time you add a HAS method:

>>> class STR(str):
...     def __radd__(self, other):
...             print "jeje"
...             return other.__add__(self)
... 
>>> 'aaaaa' + STR('bbbbb')
jeje
'aaaaabbbbb'
+3
source share
2 answers

__radd__used when the first member of the addition does not implement __add__. In the case, the intaddition is well defined by its mathematical definition, so int is trying to force another term to a number.

c str, there is no such clearly defined meaning, and the python developers decided that there was no obvious need to have something + a "string".

+5

, . , , , __radd__. __rmul__ :

>>> 4 * 'abc'
'abcabcabcabc'

, __rmod__, - . , , "Hello %s" % 'world'. . , __rsub__ str.

, , - .

+1

Source: https://habr.com/ru/post/1731678/


All Articles