为什么我收到类型错误?

时间:2017-05-17 16:40:29

标签: python

我的代码如下:

class Fraction:
"""Class for performing fraction arithmetic.
Each Fraction has two attributes: a numerator, n and a deconominator, d.
Both must be integer and the deonominator cannot be zero."""

def __init__(self, n , d):
    """Performs error checking and standardises to ensure denominator is positive"""
    if type(n)!=int or type(d)!=int:
        raise TypeError("n and d must be integers")
    if d==0:
        raise ValueError("d must be positive")
    elif d<0:
        self.n = -n
        self.d = -d
    else:
        self.n = n
        self.d = d

def __str__(self):
    """Gives string representation of Fraction (so we can use print)"""
    return(str(self.n) + "/" + str(self.d))

def __add__(self, otherFrac):
    """Produces new Fraction for the sum of two Fractions"""
    newN = self.n*otherFrac.d + self.d*otherFrac.n
    newD = self.d*otherFrac.d
    newFrac = Fraction(newN, newD)
    return(newFrac)

def __sub__(self, otherFrac):
    """Produces new Fraction for the difference between two Fractions"""        
    newN = self.n*otherFrac.d - self.d*otherFrac.n
    newD = self.d*otherFrac.d
    newFrac = Fraction(newN, newD)
    return(newFrac)

def __mul__(self, otherFrac):
    """Produces new Fraction for the product of two Fractions"""        
    newN = self.n*otherFrac.n
    newD = self.d*otherFrac.d
    newFrac = Fraction(newN, newD)
    return(newFrac)

def __truediv__(self, otherFrac):
    """Produces new Fraction for the quotient of two Fractions"""        
    newN = self.n*otherFrac.d
    newD = self.d*otherFrac.n
    newFrac = Fraction(newN, newD)
    return(newFrac)

def __eq__(self, otherFrac):
    return(self.n * otherFrac.d) == (self.d * otherFrac.n)

def gcd(self):
    gcd = 1
    if self.n % self.d == 0:
        return self.d
    for k in range(int(self.d / 2), 0, -1):
        if self.n % k == 0 and self.d % k == 0:
            gcd = k
            break
    return gcd

def simFrac(self):
    newN = self.n / f.gcd()
    newD = self.d / f.gcd()
    newFrac = Fraction(newN, newD)
    return (newFrac)

当我尝试运行simFrac()的进度时,系统会出现错误。

这是我的测试:

f=Fraction(30,18)
f.gcd()
6 #The output of f.gcd()

我们尝试输入f.simFrac()

出现错误,如下所示:

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    f.simFrac()
  File "C:/Users/Kavan/Documents/Python/resit CE/Q4.py", line 67, in simFrac
    newFrac = Fraction(newN, newD)
  File "C:/Users/Kavan/Documents/Python/resit CE/Q4.py", line 9, in __init__
    raise TypeError("n and d must be integers")
TypeError: n and d must be integers

我知道函数中的整数有一个错误(simFrac),但我不知道如何解决它,有人能告诉我该怎么做吗?

0 个答案:

没有答案