通过右侧的对象处理操作(__r*__ 方法)
Handle operation by object on right side (__r*__ methods)
当numpy.array
在右侧时,numpy
如何处理操作?
>>> [1,2,3]+numpy.array([1,2,3])
array([2, 4, 6])
我认为 list
应该尝试将 array
(使用 list.__add__
方法)添加到自身并且 失败 .
@M4rtini 回答的附加示例:__radd__
在 __add__
失败且对象类型不同时调用:
class A():
def __radd__(self, other):
return "result"
print(A()+A()) #fail with 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 A
>>result of A
>>__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 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]
当numpy.array
在右侧时,numpy
如何处理操作?
>>> [1,2,3]+numpy.array([1,2,3])
array([2, 4, 6])
我认为 list
应该尝试将 array
(使用 list.__add__
方法)添加到自身并且 失败 .
@M4rtini 回答的附加示例:__radd__
在 __add__
失败且对象类型不同时调用:
class A():
def __radd__(self, other):
return "result"
print(A()+A()) #fail with 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 A
>>result of A
>>__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 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]