Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在名为Fraction的类中使用_Python_Python 3.x - Fatal编程技术网

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
s

print(f1*f2)
@deveshkumarsing修复了hanks,我现在可以看出我的错误了,这样做要容易得多:)
分数
不是该对象的实例。您必须初始化分数对象<代码>分数(2,6)。\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu<代码>分数(2,6)*分数(1,3)