__radd__当类的实例位于添加项的右侧时,您需要实现一种方法来处理这种情况。
该文件说:
调用这些方法来实现二进制算术运算(+,-,,@,/,//,%,divmod(),pow(),*,<<,>>,&,^,|)反映(交换)的 *** 作数。仅当左 *** 作数不支持相应的 *** 作并且 *** 作数是不同类型时,才调用这些函数。例如,如果返回return
,则调用表达式以评估表达式x - y,其中y是具有__rsub__()方法的类的实例
。y.__rsub__(x)``x.__sub__(y)``NotImplemented
例:
class tInt(int): def __add__(self, other): if isinstance(other, str): return str(self) + str(other) elif isinstance(other, int): return int(self) + other elif isinstance(other, float): return float(self) + float(other) else: return NotImplemented def __radd__(self, other): return self.__add__(other)a = tInt(2)for x in ["5", 5, 5.0]: print (a + x) print (x + a)2525777.07.0
正如@chepner在评论中指出的那样,对于方法未处理的情况返回NotImplemented将导致Python尝试其他执行 *** 作的方法,如果无法执行请求的 *** 作,则引发TypeError。
在上面的代码中,的实现
__radd__很简单,因为整数加法是 关联的 ,即
2 + 3 == 3 + 2
其他类型的添加可能没有关联,在这种情况下,
__radd__将需要做的不只是委托给
__add__:
'a' + 'b' != 'b' + 'a'[0, 1] + [2, 3] != [2, 3] + [0, 1]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)