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

如何在Python的Interval类中定义运算符实现数字与区间相加?

实现数字与Interval对象的加法

当然可行,你只需要在Interval类中实现**反向加法运算符重载方法__radd__**即可解决这个问题。

原理说明

Python中执行x + y时:

  1. 首先尝试调用x.__add__(y)
  2. 如果x的__add__不支持与y的类型相加,则会尝试调用y.__radd__(x)(即反向加法)

对于1 + Interval(4,8)这种场景,int类型的__add__不知道如何处理Interval对象,因此Python会调用Interval对象的__radd__方法,把数字1作为参数传入。

代码实现

在已有的Interval类中补充以下代码即可:

class Interval:
    def __init__(self, start, end):
        self.start = start
        self.end = end

    def __add__(self, other):
        # 处理两个Interval对象相加
        if isinstance(other, Interval):
            return Interval(self.start + other.start, self.end + other.end)
        # 处理Interval + 数字的情况
        elif isinstance(other, (int, float)):
            return Interval(self.start + other, self.end + other)
        else:
            raise TypeError(f"不支持与{type(other)}类型执行加法")

    def __radd__(self, other):
        # 复用__add__的逻辑,处理数字 + Interval的情况
        return self.__add__(other)

    # 可选:添加__repr__方便直接查看结果
    def __repr__(self):
        return f"Interval({self.start}, {self.end})"

测试验证

执行以下代码验证效果:

# 测试数字 + Interval
print(1 + Interval(4, 8))  # 输出: Interval(5, 9)

# 测试Interval + 数字
print(Interval(4, 8) + 1)  # 输出: Interval(5, 9)

# 测试原有两个Interval相加逻辑
print(Interval(1,2) + Interval(10,20))  # 输出: Interval(11, 22)

这样就同时支持了数字与Interval对象的双向加法,以及原有的两个Interval对象相加的功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:11:27