【问题标题】:why a function in class do nothing but return another function in the same class?为什么类中的一个函数只返回同一个类中的另一个函数?
【发布时间】:2018-01-28 15:52:22
【问题描述】:

当我在 python 中阅读代码时,我遇到了一个让我非常困惑的问题。

class WordCloud(object):
    def fit_word(self, frequencies):
        """..."""
        return self.generate_from_frequencies(frequencies)

    def generate_from_frequencies(self, frequencies, max_font_size=None):
        """..."""
        ...

我的问题是为什么函数“fit_word”什么都不做,只返回“generate_from_frequencies”,这有什么帮助?

【问题讨论】:

  • 我们看不到整个代码。 generate_from_frequencies 可能是其他几个方法使用的通用方法,并且该方法的名称在要被其自身调用的 API 方面并不明确。在这种情况下,fit_word(作为一个名称,看起来更像是用作 API 的一部分)只需要调用一个方法。我只能推测。

标签: python function return


【解决方案1】:

这通常在您想要简化使用或对最终用户隐藏某种行为时完成。

例如:

class Text:
    def _change_color(self, r, g, b):
        self.text_color = (r, g, b)

    def change_to_yellow(self):
        self._change_color(255, 255, 0)

    def change_to_blue(self):
        self._change_color(0, 0, 255)
    .
    .
    .

您可能不希望/期望用户知道所有颜色的 RGB 代码,因此您提供了一些帮助方法来包装 _change_color 的内部行为。

话虽如此,您提供的确切示例确实似乎有点多余,因为它没有封装任何内部或复杂的行为。

另一种可能性是generate_from_frequencies 是一个通用方法,而fit_word 被认为是一个足够特殊/频繁使用的用例,值得成为它自己的方法。

例如:

class Text:
    def change_location(self, x, y):
        self.x = x
        self.y = y

    def center_text(self):
        self.change_location(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)

    def move_left(self):
        self.change_location(0, self.y)
    .
    .
    .

【讨论】:

    猜你喜欢
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2022-11-30
    相关资源
    最近更新 更多