【问题标题】:Modifying an instance of a class when it is created创建时修改类的实例
【发布时间】:2020-06-20 21:28:24
【问题描述】:

我有这个代码:

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

如上代码所示,我需要得到一个 fraction,然后在初始化后将其置于最低形式。 (我得到一个 RecursionError 并且我知道为什么)。

所以我的问题是如何将新创建的 fraction 转换为最低项(以避免在每种方法中调用 instance.lowest_form())?

【问题讨论】:

  • 永远不要分配给self。那是实际的实例对象。

标签: python-3.x oop init


【解决方案1】:

在减少to_lowest_form 方法中的分子/分母时返回Fraction 的新实例,而不是返回减少后的数字本身,只会让事情变得更复杂。考虑将简化后的数字保留为属性,在内部计算它们的简化形式。

实现示例:

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

【讨论】:

  • 谢谢@jfaccioni。做到了。 PS:你应该在“reduce”方法中缩进“return”。
  • 是的,我的错。修正了错字。
猜你喜欢
  • 2014-11-29
  • 2013-08-27
  • 2019-10-18
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多