如何在名为Fraction

时间:2019-05-24 15:41:26

标签: python python-3.x

如何在班级Fraction上使用乘法?

class Fraction(object):

    def __init__(self, num, den):
        self.num = num
        self.den = den

    def resolve(self):
        #a = 2
        #b = 6
        #c = 2
        #d = 5
        self.num = self.num / other.num
        self.den = self.den / other.den
        return self

    def __str__(self):
        return "%d/%d" %(self.num, self.den)

    def __mul__(self, other):
        den = self.den * other.num
        num = self.num * other.den
        return (Fraction(self.num * other.num, self.den * other.den))

print('Multiplication:', Fraction.__mul__(2, 6))

这是输出:

Traceback (most recent call last):
  File "app.py", line 43, in <module>
    print('Multiplication:', Fraction.__mul__(2, 6))
  File "app.py", line 27, in __mul__
    den = self.den * other.num
AttributeError: 'int' object has no attribute 'den'

1 个答案:

答案 0 :(得分:3)

尝试一下

f1 = Fraction(1, 2)
f2 = Fraction(2, 3)

print(f1 * f2)

我在这里

  • 创建类f1的对象Fraction就是1/2
  • 类似f2,即2/3
  • 现在f1 * f2自动以__mul__作为f1参数调用f2的dunder方法other
  • 因此您应该看到预期的Fraction对象已被打印

PS:之所以得到AttributeError是因为__mul__期望传递Fraction对象-当您传递int s