区间 class - Python
Interval class - Python
我应该为区间写一个class,然后我需要定义加法(如何将两个区间相加)。
我已经这样做了并且有效:
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))
无论我尝试什么都行不通。有时间的话请看一下,指点一下。我真的很感激!
您可以假设 other
已经是 Interval
并尝试添加,但如果不是则捕获异常:
def __add__ (self, other):
try:
return Interval (self.a + other.a, self.b + other.b)
except AttributeError:
pass
return Interval (self.a + int(other), self.b + int(other))
如果你想计算 42 + x
你需要 radd
方法:
def __radd__(self, other):
return self + other
如果你想同时定义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
,所以它 returns NotImplemented
,这是 Python 的提示改为尝试 Interval(a, b).__radd__(3)
。 __radd__
的定义通常不会太复杂,除非你的操作不是可交换的(也就是说,3 + Interval(a, b)
和 Interval(a, b) + 3
不相等)。
我应该为区间写一个class,然后我需要定义加法(如何将两个区间相加)。 我已经这样做了并且有效:
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))
无论我尝试什么都行不通。有时间的话请看一下,指点一下。我真的很感激!
您可以假设 other
已经是 Interval
并尝试添加,但如果不是则捕获异常:
def __add__ (self, other):
try:
return Interval (self.a + other.a, self.b + other.b)
except AttributeError:
pass
return Interval (self.a + int(other), self.b + int(other))
如果你想计算 42 + x
你需要 radd
方法:
def __radd__(self, other):
return self + other
如果你想同时定义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
,所以它 returns NotImplemented
,这是 Python 的提示改为尝试 Interval(a, b).__radd__(3)
。 __radd__
的定义通常不会太复杂,除非你的操作不是可交换的(也就是说,3 + Interval(a, b)
和 Interval(a, b) + 3
不相等)。