实现分数抽象类

时间:2015-03-05 20:12:58

标签: python fractions

我在尝试获取isZero,isNegative,互惠和否定工作时遇到了麻烦。当我测试它们时,我得到“builtins.AttributeError:'tuple'对象没有属性'倒数'。”
这四个功能是否正确实施?

我的代码,每个部分应该做什么:

class Fraction:

    # Creates a new rational number from the supplied values. The denominator must be greater than zero
    def __init__( self, numerator = 0, demoninator = 1 ) :
        self._numerator = numerator
        self._demoninator = demoninator
        # Demoninator cannot be zero
        if demoninator == 0 :
            raise ZeroDivisionError("The demoninator cannot be zero.")

        # Rational number must be stored in its smallest reduced form 
        if numerator == 0 :
            self._numerator = 0
            self._demoninator = 1
        else :
            if (numerator < 0 and demoninator >= 0 or numerator >= 0 and demoninator < 0) :
                sign = -1
            else :
                sign = 1


    # Returns a Boolean indicating if the rational number is zero
    def isZero( self ) :
        if self != 0:
            return True
        else:
            return False        

    #  Returns a Boolean indicating if the rational number is negative 
    def isNegative( self ) :
        if self < 0:
            return True
        else:
            return False

    #  Returns a new rational number that is the reciprocal of this rational number
    def reciprocal( self ) :
        reciprocal = 1 / self
        return reciprocal



    # Returns the floating-point representation of the rational number.
    # This operation is performed on the Fraction x by typecasting with the
    # float(x) function
    def __float__( self) :
        return self._numerator / self._denominator 

    # Compares this rational number to the rational number stored in
    # rhsFraction to determine their logical ordering
    def __eq__( self, rhsFraction ) :
        if self._numerator == rhsFraction._numerator and self._demonaitor ==    rhs.Frction._denominator :
            return True
        else:
            return False

    def __lt__( self, rhsFraction ) :
        if self._numerator * rhsFraction._denominator < self._demoninator * rhsFraction._numerator :
            return True
        else:
            return False

    def __le__( self, rhsFraction ) :
        return not rhsFraction < self 



    # Returns a new rational number that is the negative (-x) of this
    # rational number
    def negate( self ) :
        self = -self
        return self


    # Returns a new rational number that is the absolute version of this rational number.
    # Performed by applying the abs( x ) function to the Fraction x
    def __abs__( self ) :
        a = abs(numerator)           
        b = abs(denominator)         
        while a % b != 0 :             
            tempA = a              
            tempB = b             
            a = tempB             
            b = tempA % tempB           
        self._numerator = abs(numerator) // b * sign          
        self._denominator = abs(denominator) // b 

    # Creates and returns a new rational number that is the result of adding this rational
    # number to the given rhsFraction
    def __add__( self, rhsFraction) :
        num = (self._numerator * rhsFraction._denominator + self._denominator * rhsFraction._numerator)  
        den = self._denominator * rhsFraction._denominator       
        return Fraction(num, den) 

    # The same as the add() operation but subtracts the two rational numbers
    def __sub__( self, rhsFraction ) :
        num = (self._numerator * rhsFraction._denominator - self._denominator * rhsFraction._numerator)        
        den = self._denominator * rhsFraction._denominator       
        return Fraction(num, den) 

    # Creates and returns a new rational number that is the result of multiplying this
    # rational number to the given rhsFraction
    def __mul__( self, rhsFraction ) :
        n = self.__numerator * rhsFraction._numerator
        d = self.__denominator * rhsFraction._demoninator
        return Fraction(n, d)        

    # Creates and returns a new rational number that is the result of dividing this
    # rational number by the given rhsFraction. The rhsFraction can not be zero
    def __truediv__( self, rhsFraction ) :
        n = self._numerator / rhsFraction
        d = self._demoninator / rhsFraction
        return Fraction(n, d)

    # Returns a string representation of the rational number in the format #/#
    def __str__( self ) :
        return str(self._numerator) + "/" + str(self._demoninator)

我的代码测试:

from fractions import Fraction

FractionA = (2,-2)
FractionB = (3,-4)
f1 = Fraction(2,-2)
f2 = Fraction(3,-4)
f3 = Fraction.__add__(f1,f2)
f4 = Fraction.__sub__(f1,f2)
f5 = Fraction.__mul__(f1,f2)
f6 = Fraction.__truediv__(f1,f2)
f8 = 0
       print(Fraction.__str__(f3),Fraction.__str__(f4),Fraction.__str__(f5),Fraction.__    str__(f6), Fraction.__str__(f1), Fraction.__str__(f2))


f11 = Fraction.__eq__(f1,f2)
print(f11)

f10 = Fraction.__lt__(f1,f2)
print(f10)

f12 = Fraction.__le__(f1,f2)
print(f12)

f13 = Fraction.__abs__(f1)
print(f13)

f14 = Fraction.__abs__(f2)
print(f14)

f15 = f1.reciprocal(f1)
print(f15)

错误: 3.4.1(v3.4.1:c0e311e010fc,2014年5月18日,10:38:22)[MSC v.1600 32 bit(Intel)] Python输入“帮助”,“版权”,“信用”或“许可证”以获取更多信息。 [评估testfrac.py] -7/4 -1/4 3/4 4/3 -1 -3/4 假 真正 真正 1 3/4 回溯(最近一次调用最后一次):

builtins.AttributeError:'Fraction'对象没有属性'reciprocal'

1 个答案:

答案 0 :(得分:1)

fractions也是内置的python库的名称,另见the documentation。所以你实际上并没有测试你的分数类,而是内置的。但这并不能提供您尝试调用的reciprocal。将文件命名为不同的文件myfractions,然后按

导入
from myfractions import Fractions

再次运行测试。