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

如何为Python类定义classmethod类型的__rsub__特殊方法?

问题解决:为类定义__rsub__实现50 - percent创建实例

先梳理你代码里的几个关键问题:

  1. __repr__方法错误引用了局部变量value,应该使用实例属性self.value,否则会触发NameError。
  2. __rsub__的返回类型标注错误,应该是percent而非None;参数名用other指代左操作数(示例中的50)语义更清晰。
  3. 需确保__rsub__的逻辑正确返回类实例。

修正后的代码如下:

class percent:
    def __init__(self, value: int) -> None:
        self.value = value

    @classmethod
    def __rsub__(cls, other: int) -> 'percent':
        # other是左操作数(比如50),返回对应的percent实例
        return cls(other)

    def __repr__(self) -> str:
        return f"{self.value}%"

测试执行效果:

>>> 50 - percent
50%

原理说明:
当执行50 - percent时,Python首先尝试调用左操作数(int类型的50)的__sub__方法,但int的__sub__不支持直接减去类对象,因此会转而调用右操作数(percent类)的__rsub__方法。由于我们用@classmethod定义了__rsub__,此时cls就是percent类,接收左操作数other(即50)后返回percent(50)实例,最终通过__repr__输出50%。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 22:32:53