我正确实施__radd__吗?

时间:2016-03-17 00:29:28

标签: python class

我正在尝试将__radd_实现到我的Fractions类中,但我不确定我是否完全理解它是如何工作的。此外,每次我尝试运行以下程序时都会出错。据我了解,如果add函数不适用,则使用__radd_,但我的程序直接进入__add_,甚至不尝试__radd _。

enter image description here

class Fraction:
num = 0
den = 0

def __init__(self, top, bottom):
    if not isinstance(top, int) or not isinstance(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)

#__radd__ is REVERSE add. It is used when obj.__add__(other) is not applicable, when the operand on the left is an
#instance of an object and the one on the right isn't. It will become other.__radd__(obj).
def __radd__(self, other):
    newNum = self.num + other
    newDen = self.den + other

    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, 58)

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)
print(frac + 1) 

0 个答案:

没有答案