You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何重载Python二元运算符,支持类A作为右操作数的乘法?

解决类A支持双向标量乘法的问题

要让float * A实例也能正常工作,你需要实现Python的__rmul__特殊方法——当左侧操作数(比如这里的float)没有定义与右侧操作数(A实例)的乘法逻辑时,Python会自动调用右侧实例的__rmul__方法来完成运算。

具体修改方案:

  1. 优化__mul__中的类型判断:用isinstance替代直接的type比较,这样既支持子类,也能兼容int类型(比如2 * A(3)这种场景)。
  2. 实现__rmul__方法,直接复用__mul__的逻辑,确保a * b和b * a(当其中一个是标量时)行为完全一致。
  3. 明确抛出TypeError并附带提示信息,替代原来的无参raise。

修改后的完整代码:

class A:
    def __init__(self, value: float):
        self.value = value

    def __mul__(self, other):
        if isinstance(other, A):
            return A(self.value * other.value)
        elif isinstance(other, (float, int)):
            return A(self.value * other)
        else:
            raise TypeError(f"不支持与类型{type(other)}的对象相乘")

    def __rmul__(self, other):
        # 复用__mul__逻辑,保证左右操作数行为一致
        return self.__mul__(other)

测试验证:

a1 = A(2.0)
a2 = A(3.0)

# 原有的支持场景
print((a1 * a2).value)  # 输出6.0
print((a1 * 4.0).value) # 输出8.0

# 新增支持的场景
print((5.0 * a1).value) # 输出10.0
print((3 * a2).value)   # 输出9.0

这样无论A实例是在乘法的左边还是右边,标量乘法和实例间乘法都能正常工作,且行为完全一致。

内容的提问来源于stack exchange,提问作者user8171079

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 03:52:11