我对运算符重载很新,我不清楚如何将Fraction对象与整数进行比较。我运行了一个assert测试(FractionOb< 0)== false,我得到了一个断言错误。如何设计一个将分数与整数进行比较的lt方法?
`
班级分数: def init (self,numerator = 0,denominator = 1): “”” 将分数初始化为分子和分母 构造函数提供的值。
numerator - value of numerator with a default value of 0.
The type must be of integer.
denomenator - value of denomenator with a default value of 1.
The type must be of integer.
'''
if not isinstance(denominator,int):
raise TypeError("denominator must be of type int!")
if not isinstance(numerator,int):
raise TypeError("numerator must be of type int!")
if denominator == 0:
raise ZeroDivisionError("Denominator cannot be 0")
self.numer = numerator
self.denom = denominator
self.normalize()
def __str__(self):
s = "%d /% d" % (self.numer,self.denom)
return s
def normalize(self):
reduce = Fraction.gcd(self.numer, self.denom)
self.numer = self.numer // reduce
self.denom = self.denom // reduce
#When testing the GCD of a certain fraction create a new one like (x = Fraction) with no parameters. Then invoke the method with (x.gcd(a,b))..
#This will find the greatest common denominator
def gcd(a,b):
while b:
a, b = b, a%b
return a
# necessary to define so that it is usable on hashable
# collections like set, dict, etc..
def __hash__(self):
'''' returns the hash of the fraction equivalent to
the hash of the floating point number the fraction represents.
'''
return hash(self.numer/self.denom) # use hash of floating point equiv.
# comparison operators
def __lt__(self,other):
''' returns True if this fraction is less than the other
fraction, false otherwise.
'''
if not isinstance(other,Fraction):
return NotImplemented
return self.numer*other.denom < other.numer*self.denom
#Returns true if fracrion is less or equal to other fraction and false otherwise
def __le__(self,other):
''' returns True if this fraction is less than or equal
to the other fraction, false otherwise.
'''
if not isinstance(other,Fraction):
return NotImplemented
return self.numer*other.denom <= other.numer*self.denom
#Tests if one fraction is equal to the other
def __eq__(self, other):
if not isinstance(other,Fraction):
return NotImplemented
return self.numer*other.denom == other.numer*self.denom
#Tests if on fraction is not equal to the other
def __ne__(self, other):
if not isinstance(other,Fraction):
return NotImplemented
return self.numer*other.denom != other.numer*self.denom
#Return true if fraction is greater than other fraction.. If not it will return false
def __gt__(self, other):
if not isinstance(other,Fraction):
return False
return self.numer*other.denom > other.numer*self.denom
#Returns true if the fraction is less than or equal to fraction and false if it is not
def __ge__(self, other):
if not isinstance(other,Fraction):
return NotImplemented
return self.numer*other.denom >= other.numer*self.denom
`
答案 0 :(得分:1)
将int
转换为具有相同分母的Fraction
,然后进行比较。