处理右侧对象的操作(__r * __方法)

时间:2016-01-28 10:49:50

标签: python operator-overloading operators

numpy位于右侧时,numpy.array如何处理操作?

>>> [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

1 个答案:

答案 0 :(得分:0)

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)
     

调用这些方法来实现二进制算术运算   (+, - ,*,/,%,divmod(),pow(),**,<<,>>,&,^,|)反映   (交换)操作数。 仅在左侧调用这些函数   操作数不支持相应的操作和操作数   属于不同类型。 [2]