Python 如何在名为Fraction的类中使用
如何使乘法与我的类Python 如何在名为Fraction的类中使用,python,python-3.x,Python,Python 3.x,如何使乘法与我的类分数 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 s
分数
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'
回溯(最近一次呼叫最后一次):
文件“app.py”,第43行,在
打印(‘乘法:’,分数._umul___(2,6))
文件“app.py”,第27行,在__
den=self.den*other.num
AttributeError:“int”对象没有属性“den”
试试这个
f1 = Fraction(1, 2)
f2 = Fraction(2, 3)
print(f1 * f2)
我来了
- 创建类
分数的对象f1
,这是1/2
- 同样的
f2
是2/3
- 现在
f1*f2
自动调用f1
的dunder方法\uuuuuuuuuuuuuuu
,并将f2
作为其他
参数
- 因此,您应该看到打印的预期
分数对象
PS:你之所以会得到属性错误是因为,\uuuuuMul\uuuuuuuuuuuuuuuuuuuuuuu
需要传递分数
对象-当你传递int
sprint(f1*f2)
@deveshkumarsing修复了hanks,我现在可以看出我的错误了,这样做要容易得多:)分数
不是该对象的实例。您必须初始化分数对象<代码>分数(2,6)。\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu<代码>分数(2,6)*分数(1,3)