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

如何实现Python数据类Person实例的减法运算?

实现Python数据类的减法运算符支持

要实现Person(100) - 10返回Person(moneyInTheBank=90)的需求,使用魔法方法是最简便直接的方案,getter/setter无法支持运算符重载,没法实现这种简洁的语法调用。

具体实现代码

只需在Person类中重写__sub__魔法方法,该方法会在使用-运算符时被自动调用,返回一个新的Person实例:

from dataclasses import dataclass

@dataclass
class Person:
    moneyInTheBank: float

    def __sub__(self, amount: float) -> 'Person':
        # 可选:添加参数类型校验,避免非法运算
        if not isinstance(amount, (int, float)):
            raise TypeError("仅支持与数值类型执行减法操作")
        # 返回新实例,不修改原对象(保持不可变性更安全)
        return Person(self.moneyInTheBank - amount)

测试验证

运行以下代码即可看到效果:

p = Person(100)
result = p - 10
print(result)  # 输出: Person(moneyInTheBank=90.0)

为什么不选getter/setter?

如果用getter和setter,你只能手动定义类似deduct_money这样的方法,调用时需要写成p.deduct_money(10),完全没法实现Person(100)-10这种直观的运算符语法,不符合你的需求。

可选扩展:支持反向减法(如果需要)

如果要支持10 - Person(100)这类右操作数是Person的场景,可以额外重写__rsub__方法:

def __rsub__(self, amount: float) -> 'Person':
    if not isinstance(amount, (int, float)):
        raise TypeError("仅支持与数值类型执行减法操作")
    return Person(amount - self.moneyInTheBank)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 09:30:51