自定义类型IntervalMath的实例a,求a/2可以进入类的内置函数__truediv__,而2/a进不去__rdiv__,只能在外面将2转化为IntervalMath类型。 否则会报错:TypeError: unsupported operand type(s) for /: ‘int’ and 'IntervalMath’ 但a/2时就不会报错。
"""
Created on Wed Mar 9 21:10:37 2022
@author: REESE
"""
class IntervalMath:
def __init__(self,lower=0,upper=0):
self.lo = float(lower)
self.up = float(upper)
def __add__(self,other):
a,b,c,d = self.lo,self.up,other.lo,other.up
I = IntervalMath()
I.lo = a + c
I.up = b + d
return I
def __sub__(self,other):
a,b,c,d = self.lo,self.up,other.lo,other.up
return IntervalMath(a-d,b-c)
def __mul__(self,other):
if isinstance(other, (int, float)):
other = IntervalMath(other, other)
a,b,c,d = self.lo,self.up,other.lo,other.up
x,y = min(a*c,a*d,b*c,b*d), max(a*c,a*d,b*c,b*d)
return IntervalMath(x,y)
def __rmul__(self,other):
if isinstance(other, (int,float)):
other = IntervalMath(other,other)
return other*self
def __truediv__(self,other):
if isinstance(other,(int,float)):
other = IntervalMath(other,other)
a,b,c,d = self.lo,self.up,other.lo,other.up
if c*d == 0:
return 'error'
else:
x,y = min(a/c,a/d,b/c,b/d), max(a/c,a/d,b/c,b/d)
return IntervalMath(x,y)
def __rdiv__(self,other):
return other/self
'''a, b, c, d = other.lo, other.up, self.lo, self.up
if c * d == 0:
return 'error'
else:
x, y = min(a / c, a / d, b / c, b / d), max(a / c, a / d, b / c, b / d)
return IntervalMath(x, y)'''
def __str__(self):
return '[%g, %g]' % (self.lo, self.up)
a = IntervalMath(4,5)
print((a*2).lo,(a*2).up)
print((2*a).lo,(2*a).up)
print((a/2).lo,(a/2).up)
other = 2
other = IntervalMath(other,other)
print((other/a).lo,(other/a).up)
问题虽已解决,但还是不太明白原因,下周一跟老师讨论一下后补充。
|