python实现Rational类的+、-、*、/以及Rich comparision方法(即可以进行>=、>、<=、<、==、!=等复比较操作
思路分析:利用functools total_ordering实现整套复比较操作。只要实现__eq__()和(ge()、gt()、le()、lt())中的一个即可,其他的可通过取反得知结果。
代码展示
classes xmath.py
from functools import total_ordering
@total_ordering
class Rational:
def __init__(self,numer,denom):
self.numer=numer
self.denom=denom
def __add__(self, other):
return Rational(
self.numer*other.denom+self.denom*other.numer,
self.denom*other.denom
)
def __sub__(self, other):
return Rational(
self.numer*other.denom-self.denom*other.numer,
self.denom*other.denom
)
def __mul__(self, other):
return Rational(
self.numer*other.numer,
self.denom*other.denom
)
def __truediv__(self, other):
return Rational(
self.numer*other.denom,
self.denom*other.denom
)
def __eq__(self, other):
if self is other:
return True
elif self.numer/self.denom==other.numer/other.denom:
return True
else:
return False
def __gt__(self, other):
return self.numer/self.denom>other.numer/other.denom
def __str__(self):
return '{}/{}'.format(self.numer,self.denom)
def __repr__(self):
return 'Rational({},{})'.format(self.numer,self.denom)
classes xmath_demo.py
import xmath
m=xmath.Rational(2,3)
n=xmath.Rational(4,6)
x=xmath.Rational(2,7)
print('m=2/3,n=4/6,x=2/7')
print('m+x=',m+x)
print('m-x=',m-x)
print('m*x=',m*x)
print('m/x=',m/x)
print('m==m is',m==m)
print('m==n is',m==n)
print('m==x is',m==x)
print('m!=x is',m!=x)
print('m>x is',m>x)
print('m>=x is',m>=x)
print('m<x is',m<x)
print('m<=x is',m<=x)
运算结果:
m=2/3,n=4/6,x=2/7
m+x= 20/21
m-x= 8/21
m*x= 4/21
m/x= 14/21
m==m is True
m==n is True
m==x is False
m!=x is True
m>x is True
m>=x is True
m<x is False
m<=x is False