自定义类型IntervalMath的实例a,求a/2可以进入类的内置函数__truediv__,而2/a进不去__rdiv__,只能在外面将2转化为IntervalMath类型。
否则会报错:TypeError: unsupported operand type(s) for /: ‘int’ and 'IntervalMath’
但a/2时就不会报错。
# -*- coding: utf-8 -*-
"""
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
#方法1
#return IntervalMath(a+c,b+d) #相当于new了一个IntervalMath实例
#方法2
I = IntervalMath() #__init__函数参数有默认值,此时有();若无默认值,声明一个没有参数的实例时,不加()
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)): #实用程序函数,用于检查对象是否为特定类型,此处为判断Object 'other'是否为int或者float中的一种
other = IntervalMath(other, other) # 例:other==2 ==》 other == I[2,2]
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): #针对2*y0
if isinstance(other, (int,float)):
other = IntervalMath(other,other)
return other*self
def __truediv__(self,other):
if isinstance(other,(int,float)): #为了实现a/2
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):#针对2/a
#if isinstance(other,(int,float)): #为了实现2/a
# other = IntervalMath(other,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)
#实现2/a
other = 2
other = IntervalMath(other,other)
print((other/a).lo,(other/a).up)
#但我有个疑问,为什么print((2/a).lo,(2/a).up) 进不去a的内置函数__rdiv__中,而只能先在外面把2转化为IntergralMath类型。而a/2不必如此
问题虽已解决,但还是不太明白原因,下周一跟老师讨论一下后补充。