首页 > 解决方案 > 如何将一个类方法的值返回给同一类的其他方法

问题描述

下面是我的课程,我想将函数 add() 中的 n 和 d 的值返回给函数 simple() 以便在计算 GCD 后返回分数,我该怎么做?另外,我不能只在 simple 中调用 add 函数,因为我必须为所有其他计算添加函数 下面是代码:

class Fraction:
    def __init__(self, num, denom) -> None:  
    
        self.num = num 
        self.denom = denom 
        if self.denom == 0:
            raise ZeroDivisionError("cannot divide by zero")

    def __add__(self, other: "Fraction") -> "Fraction": 

        n: int = self.num * other.denom + self.denom * other.num
        d: int = self.denom * other.denom

    def simplify(self) -> "Fraction":

        n1: Fraction = abs(self.num)
        n2: Fraction= abs(self.denom)
        gcd: int = 1
        k:int = 1
        while k <= n1 and k <= n2:
            if n1 % k == 0 and n2 % k == 0:
                gcd = k
            k += 1
       a:int = self.num / gcd
       b:int = self.denom / gcd
       new = Fraction(a,b)
       return new

标签: pythonpython-3.xfunctionclassself

解决方案


推荐阅读