将运算符分配给嵌入的类函数

时间:2017-03-03 16:19:20

标签: python function class

我正在为我的入门python类做一个家庭作业。 目标是定义使用* / + - <的函数。 > < => =具有类调用的运算符。这个特殊程序需要3个参数self, inches, numerator, denominator并将分母存储为64(如果可以简化)

致电RulerUnit(2, 1, 4)将返回"2 1/4"

我正在处理乘法部分,当inches等于0

时遇到问题

inches == 0还是inches is None

此外,无论情况如何,当我执行断言时,例如: assert(str(RulerUnit(2, 3, 4) * RulerUnit(0, 1, 2)) == "1 3/8")

AssertionError被激怒,我的代码

print((RulerUnit(2, 3, 4) * RulerUnit(0, 1, 2)))

打印2 3/8

代码:

def __mul__ (self, other):

    if self.inches == 0 and other.inches == 0:
        newnum = self.num * other.num
        finaldenom = self.denom * other.denom
        finalnum = newnum % 64
        finalinches = newnum // finaldenom
        return RulerUnit(finalinches, finalnum, finaldenom)

    elif self.inches == 0 and other.inches != 0:
        newnum1 = (self.inches * self.denom) + self.num
        finaldenom = self.denom * other.denom
        finalnum = (newnum1 * other.num) % 64
        finalinches = (newnum1 * other.num) // finaldenom
        return RulerUnit(finalinches, finalnum, finaldenom)

    elif self.inches!= 0 and other.inches == 0:
        newnum1 = (self.inches * self.denom) + self.num
        finaldenom = self.denom * other.denom
        finalnum = (newnum1 * other.num) % 64
        finalinches = (newnum1 * other.num) // finaldenom
        return RulerUnit(finalinches, finalnum, finaldenom)

    elif self.inches != 0 and other.inches != 0:
        newnum1 = (self.inches * self.denom) + self.num
        newnum2 = (other.inches * other.denom) + other.num
        finaldenom = (self.denom * other.denom) % 64
        finalnum = (newnum1 * newnum2) % 64
        finalinches = (newnum1 * newnum2) // finaldenom
        return RulerUnit(finalinches, finalnum, finaldenom)

2 个答案:

答案 0 :(得分:0)

您应该规范化存储值的方式。 2 3/8真的是19/8。一旦你这样做,数学是微不足道的。使用混合数字作为输入和输出,但在内部使用纯分数。

std::function<int(std::string)> testFunctionB=testFunctionA(2.3,std::string b);

答案 1 :(得分:0)

当您的某个值的inches部分为零时,不需要特殊情况。你可以在计算中使用零,它应该正确:

def __mul__(self, other):
    num = (self.inches * self.denom + self.num) * (other.inches * other.denom + other.num)
    denom = self.denom * other.denom
    inches, num = divmod(num, denom)
    return RulerUnit(inches, num, denom)