我创建了一个名为“Fraction”的类,在它的构造函数中,我希望能够测试并查看分子或分母是否不是整数。我写了一个if else语句来引发错误或创建一个对象,但无论是否为整数,我都会收到错误。另外,如果我输入一个字符串,我会得到一个完全不同的错误,例如,这似乎根本不起作用。这是正确的实施吗?
class Fraction:
num = 0
den = 0
def __init__(self, top, bottom):
if top != int or bottom != int:
raise RuntimeError("Bad value for top or bottom")
else:
gcd, remainder = 0, 0
n, m = top, bottom
while (n != 0):
remainder = m % n
m = n
n = remainder
gcd = m
self.num = top // gcd
self.den = bottom // gcd
def show(self):
print(self.num, "/", self.den)
def __str__(self):
return str(self.num) + "/" + str(self.den)
def getNum(self):
print(self.num)
def getDen(self):
print(self.den)
def __add__(self, otherFraction):
newNum = self.num*otherFraction.den + self.den * otherFraction.num
newDen = self.den * otherFraction.den
return Fraction(newNum, newDen)
def __sub__(self, otherFraction):
newNum = self.num * otherFraction.den - self.den * otherFraction.num
newDen = self.den * otherFraction.den
return Fraction(newNum, newDen)
def __mul__(self, otherFraction):
newNum = self.num * otherFraction.num
newDen = self.den * otherFraction.den
return Fraction(newNum, newDen)
def __truediv__(self, otherFraction):
newNum = self.num * otherFraction.den
newDen = self.den * otherFraction.num
return Fraction(newNum, newDen)
def __gt__(self, other):
return ((self.num * other.den) > (self.den * other.num))
def __ge__(self, other):
return ((self.num * other.den) >= (self.den * other.num))
def __lt__(self, other):
return ((self.num * other.den) < (self.den * other.num))
def __le__(self, other):
return ((self.num * other.den) <= (self.den * other.num))
def _ne__(self, other):
return ((self.num * other.den) != (self.den * other.num))
frac = Fraction(5, 16)
frac2 = Fraction(3, 16)
print(frac.show())
print(frac.getNum())
print(frac.getDen())
print(frac + frac2)
print(frac - frac2)
print(frac * frac2)
print(frac / frac2)
print(frac > frac2)
print(frac >= frac2)
print(frac < frac2)
print(frac <= frac2)
print(frac != frac2)
答案 0 :(得分:1)
使用isinstance
代替相等。
if not(isinstance(top,int) and isinstance(bottom, int)):