如何在班级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'
答案 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