类定义中非整数的异常处理

2024-10-08 22:22:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个名为“分数”的类,在它的构造函数中,我希望能够测试并查看分子或分母是否不是整数。我编写了一个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)

Tags: selfreturntopdefnumotherprintfrac

热门问题