views:

93

answers:

2

str has other methods like __rmod__, __rsub__ or __rmul__

int did have a __radd__ method

Weird, and I'd like to know why.

Example radd beeing called when first term HAS add method:

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

__radd__ is used when the first term of the addition does not implement __add__. In the case of int, addition is well defined by its mathematical definition, and so int tries to coerce the other term into a number.

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

TokenMacGuy
are you sure? In the example added to the question \_\_radd__ is used and the first term do have \_\_add__.
Juanjo Conti
In the specific case of str + STR, STR is a subclass of str, since that provides a more specific method, it is used in preference to str.__add__
TokenMacGuy
Could you explain it a bit more for me please?
Juanjo Conti
+1  A: 

Types only define methods that they use. Since the only objects that can be added to strings are other strings or unicode objects, there is no need for a general __radd__ method. __rmul__ allows you to duplicate strings:

>>> 4 * 'abc'
'abcabcabcabc'

I'm not sure why __rmod__ is needed, but it is somehow related to formatting. Perhaps it eases the implementation of formatting with a single argument, as in "Hello %s" % 'world'. I'm not sure. Contrary to your assertion, there is no __rsub__ on str objects.

In short, those methods are only defined if they actually do something.

jcdyer