为何Python中__rsub__执行减法时会出现反向运算问题?
问题原因与解决方法
核心原因
当执行[1, 2, 3] - CustomList([2, 4, 6])时,Python会触发CustomList的__rsub__方法。这个方法的参数顺序是(self, other),其中self是右边的CustomList([2,4,6]),other是左边的普通list[1,2,3]。
如果你的__rsub__实现错误地计算了self - other(即CustomList([2,4,6]) - [1,2,3]),结果自然会是[1,2,3],和预期的other - self完全相反。
错误示例(导致反向的写法)
比如你可能这么写了__rsub__:
def __rsub__(self, other): return self - other
这会直接用右边的CustomList减左边的普通list,完全搞反了运算逻辑。
正确实现方式
方式一:直接实现other - self的逻辑
class CustomList(list): def __sub__(self, other): max_len = max(len(self), len(other)) result = [] for i in range(max_len): val1 = self[i] if i < len(self) else 0 val2 = other[i] if i < len(other) else 0 result.append(val1 - val2) return CustomList(result) def __rsub__(self, other): max_len = max(len(self), len(other)) result = [] for i in range(max_len): val1 = other[i] if i < len(other) else 0 val2 = self[i] if i < len(self) else 0 result.append(val1 - val2) return CustomList(result)
方式二:复用__sub__方法,交换操作数
把左边的普通list转成CustomList实例,再调用__sub__:
class CustomList(list): def __sub__(self, other): max_len = max(len(self), len(other)) result = [] for i in range(max_len): val1 = self[i] if i < len(self) else 0 val2 = other[i] if i < len(other) else 0 result.append(val1 - val2) return CustomList(result) def __rsub__(self, other): # 将普通list转为CustomList,再执行减self的操作 return CustomList(other) - self
这样修改后,[1,2,3] - CustomList([2,4,6])就会正确返回CustomList([-1,-2,-3])。
内容的提问来源于stack exchange,提问作者zaelcovsky
相关产品推荐
相关产品推荐

