如何为Python类定义classmethod类型的__rsub__特殊方法?
问题解决:为类定义
__rsub__实现50 - percent创建实例 先梳理你代码里的几个关键问题:
__repr__方法错误引用了局部变量value,应该使用实例属性self.value,否则会触发NameError。__rsub__的返回类型标注错误,应该是percent而非None;参数名用other指代左操作数(示例中的50)语义更清晰。- 需确保
__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
相关产品推荐
相关产品推荐

