python - 区间类 - Python

标签 python class intervals

我应该为区间写一个类,然后我需要定义加法(如何将两个区间相加)。 我已经这样做了并且有效:

def __add__ (self, other):
    return Interval (self.a + other.a, self.b + other.b) 

其中 a 和 b 是一个区间的终点。

现在我需要修改代码,以便定义间隔和数字 c(float 或 int)之间的加法。

[a,b] + c = [a+c,b+c] 和

c + [a,b] = [a+c,b+c].

我试过很多东西都不行,比如:

def __add__ (self, other, *args):
        if args:
            return Interval (self.a + other.a, self.b + other.b)
        else:
            return  Interval (self.a + int(number), self.b + int(number)) 

无论我尝试什么都行不通。有时间的话请看一下,指点一下。我真的很感激!

最佳答案

如果你想同时定义 Interval(a, b) + Interval(c, d)Interval(a, b) + c(对于一些非Interval类型的c),你需要检查定义中的参数other

def __add__(self, other):
    if instanceof(other, Interval):
        return Interval(self.a + other.a, self.b + other.b)
    elif instanceof(other, (int, float)):
        return Interval(self.a + other, self.b + other)
    else:
        return NotImplemented

要同时支持 c + Interval(a, b),您需要定义 __radd__:

def __radd__(self, other):
    return self + other

如果你对 3 + Interval(a, b)3.__add__(Interval(a, b)) 不知道如何处理 Interval,所以它返回 NotImplemented,这是 Python 尝试 Interval(a, b).__radd__(3) 的提示。 __radd__ 的定义通常不会太复杂,除非您的操作不是可交换的(即 3 + Interval(a, b)Interval( a, b) + 3 不相等)。

关于python - 区间类 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59215736/

相关文章:

python - 模板在 django 中不起作用

python-3.x - 在 Python 中更改另一个类中的属性

c++ - 类和更新数据

python - 你如何在 Python 中表达二进制文字?

python - 从笔记本中清除 Jupyter 笔记本中单元格的小部件区域

jquery - 如何每 15 秒刷新一次 Twitter API?

python - 间隔中的天数总和

ios - 以不同速度闪烁事物的最佳方式(性能方面)是什么?

python - 以递归方式评估 json 的优雅方法

python - 从属性列表动态创建属性到类