在创建类的实例时对其进行修改

时间:2020-03-08 23:13:56

标签: python-3.x oop init

我有此代码:

class Fraction:
    def __init__(self, top, bottom):
        self.num = top
        self.den = bottom
        self = self.to_lowest_form()

    def to_lowest_form(self):
        from math import gcd

        d = 0
        while d != 1:
            d = gcd(self.num, self.den)
            self.num //= d
            self.den //= d

        return Fraction(self.num, self.den)

    def __add__(self, other):
        pass

如上面的代码所示,我需要获取分数,然后在初始化后将其置于最低形式。 (我收到一个 RecursionError ,我知道为什么)。

所以我的问题是如何将新创建的分数转换为其最低期限(以避免在每种方法中调用 instance.lowest_form())?< / p>

1 个答案:

答案 0 :(得分:1)

通过在Fraction方法中减少分子/分母时返回to_lowest_form的新实例,而不是返回减少后的数字,只会使事情变得更加复杂。考虑将精简数字保留为属性,然后 在内部计算其精简形式。

实施示例:

from math import gcd

class Fraction:
    def __init__(self, top, bottom):
        self.num, self.den = self.reduce(num=top, den=bottom)

    @staticmethod
    def reduce(num, den):
        d = 0
        while d != 1:
            d = gcd(num, den)
            num //= d
            den //= d
        return num, den