0

How does numpy can handle operations, when numpy.array is on the right side?

>>> [1,2,3]+numpy.array([1,2,3])
array([2, 4, 6])

I thought list should try to add array (with list.__add__ method) to itself and fail.


Additional example to @M4rtini's answer: __radd__ is called when __add__ fails and objects are of different types:

class A():
    def __radd__(self, other):
        return "result"
print(A()+A()) #fail with TypeError
Winand
  • 2,093
  • 3
  • 28
  • 48

1 Answers1

1
class A(object):
    def __radd__(self, other):
        print ("__radd__ called of A")
        return "result of A"

class B(object):
    def __radd__(self, other):
        print ("__radd__ called of B")
        return "result of B"


print (B()+A())
print (A()+B())

>>__radd__ called of A
>>result of A
>>__radd__ called of B
>>result of B

Documentation

object.__radd__(self, other)
object.__rsub__(self, other)
object.__rmul__(self, other)
object.__rdiv__(self, other)
object.__rtruediv__(self, other)
object.__rfloordiv__(self, other)
object.__rmod__(self, other)
object.__rdivmod__(self, other)
object.__rpow__(self, other)
object.__rlshift__(self, other)
object.__rrshift__(self, other)
object.__rand__(self, other)
object.__rxor__(self, other)
object.__ror__(self, other)

These methods are called to implement the binary arithmetic operations (+, -, *, /, %, divmod(), pow(), **, <<, >>, &, ^, |) with reflected (swapped) operands. These functions are only called if the left operand does not support the corresponding operation and the operands are of different types. [2]

M4rtini
  • 13,186
  • 4
  • 35
  • 42
  • Where is it stated in Python docs that `__radd__` is called on fail, and that it's not called with objects of the same types? i couldn't figure that out for several days:) – Winand Jan 28 '16 at 11:41
  • Clearly stated, my fault – Winand Jan 28 '16 at 11:47