首页 > 解决方案 > 如何在名为 Fraction 的类中使用 __mul__

问题描述

如何使乘法与我的班级一起工作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'

标签: pythonpython-3.x

解决方案


尝试这个

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

print(f1 * f2)

我在这里

  • 创建一个f1类对象Fraction1/2
  • 同样f22/3
  • 现在f1 * f2自动调用with的dunder 方法__mul__作为参数f1f2other
  • 所以你应该看到预期的Fraction对象被打印出来

PS:你得到的原因AttributeError是因为,__mul__期望Fraction对象被传递 - 当你传递ints


推荐阅读