'''
* 自定义一个Ration类(有理数类)
* 把有理数的正负判断功能移动到分子,把分数看作数组other [0]=分子,[1]=分母
* 运算符重载还有 __mod__(self)求余.__contians__(self,value)检查其成员资格,在本例中没体现
'''
def gcd(a,b):#考虑到正负数,需要每次递归都要把a,b取绝对值
a=abs(a)
b=abs(b)
if a<b:
a,b=b,a
if b ==0:
return a
else:
return gcd(b,a%b)
class Ration:
def __init__(self,numberator=0,denominator=1):#分子,分母
divisor=gcd(numberator,denominator)
self.__numberator=(1 if denominator >0 else -1)*int(numberator/divisor)
self.__denominator=int(abs(denominator)/divisor)
# + - * /:
def __add__(self,secondRation):
n= self.__numberator * secondRation[1]+ self.__denominator * secondRation[0]
m= self.__denominator*secondRation[1]
return Ration(n,m)
def __sub__(self,secondRation):
n=self.__numberator*secondRation[1]-self.__denominator*secondRation[0]
m=self.__denominator*secondRation[1]
return Ration(n,m)
def __mul__(self,secondRation):
n=self.__numberator*secondRation[0]
m=self.__denominator*secondRation[1]
return Ration(n,m)
def __truediv__(self,secondRation):
n=self.__numberator*secondRation[1]
m=self.__denominator*secondRation[0]
return Ration(n,m)
# 返回格式
def __float__(self):
return self.__numberator/self.__denominator
def __int__(self):
return int(self.__float__())
def __str__(self):
if self.__denominator==1:
return str(self.__numberator)
else :
return str(self.__numberator)+"/"+str(self.__denominator)
def __getitem__(self,index):
#下标运算符
if index==0:
return self.__numberator
else:
return self.__denominator
#比较
def __cmp__(self,secondRation):
temp=self.__sub__(secondRation)
if temp[0]>0:
return 1
elif temp[0]==0:
return 0
else:
return -1
def __lt__(self,secondRation):
return self.__cmp__(secondRation)<0
def __le__(self,secondRation):
return self.__cmp__(secondRation)<=0
def __eq__(self,secondRation):
return self.__cmp__(secondRation)==0
def __ne__(self,secondRation):
return self.__cmp__(secondRation)!=0
def __gt__(self,secondRation):
return self.__cmp__(secondRation)>0
def __ge__(self,secondRation):
return self.__cmp__(secondRation)>=0
def main():
r1=Ration(4,2)
r2=Ration(2,3)
print(r1,"+",r2,"=",r1+r2)
print(r1,"-",r2,"=",r1-r2)
print(r1,"*",r2,"=",r1*r2)
print(r1,"/",r2,"=",r1/r2)
print(r1>r2)
print(r1==r2)
print(r1<r2)
main()
python运算符重载案例
最新推荐文章于 2024-07-15 17:25:56 发布