python - Handle operation by object on right side (__r*__ methods) -
how numpy can handle operations, when numpy.array on right side?
>>> [1,2,3]+numpy.array([1,2,3]) array([2, 4, 6]) i thought list should try add array (with list.__add__ method) , fail.
additional example @m4rtini's answer: __radd__ called when __add__ fails , objects of different types:
class a(): def __radd__(self, other): return "result" print(a()+a()) #fail typeerror
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 >>result of >>__radd__ called of b >>result of b 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 called implement binary arithmetic operations (+, -, *, /, %, divmod(), pow(), **, <<, >>, &, ^, |) reflected (swapped) operands. these functions called if left operand not support corresponding operation , operands of different types. [2]
Comments
Post a Comment