什么是长 class 名称的最佳命名约定?

What is best naming conventions for long class name?

现在,我正在为 MVC 模式编写 Python-flask 代码。 但是,我自己考虑,我认为控制器的声明符 class 太长了

比如我有

class GoogleQuestionController:
    def __init__(self):

        (.....)

class YahooQuestionController:
    def __init__(self):

        (.....)

两个非常相似的 class 名称,所以我不能像

这样定义声明符
question_controller = GoogleQuestionController()

以上。

定义 class 声明符的最佳建议是什么?

google_question_controller = GoogleQuestionController()
yahoo_question_controller = YahooQuestionController()

这段代码太长了,

所以,我现在就是这样用的

yq_con = YahooQuestionController()
gq_con = GoogleQuestionController()

gqc = GoogleQuestionController()
yqc = YahooQuestionController()

也许这不是您要找的答案,但我强烈建议您实际选择:

google_question_controller = GoogleQuestionController()
yahoo_question_controller = YahooQuestionController()

我不认为这太长,它实际上可读且整洁。

现在,抛开意见,请记住 PEP 8 对长度没有限制,但高度重视变量的可读性:

Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.

上下文在这里很重要:

google_question_controller = GoogleQuestionController()
yahoo_question_controller = YahooQuestionController()

可能没问题,但如果我们能够重构以使名词不模糊,即如果只有一个 google 对象,我可能会使用:

google = GoogleQuestionController()
yahoo = YahooQuestionController()

同样,如果动词没有歧义,例如如果我在 Google object/module 中,我会使用 question(或者 controller):

class GoogleSomething(object):
    def __init__(self):
        self.question = GoogleQuestionController()  # or perhaps `controller`

class YahooSomething(object):
    def __init__(self):
        self.question = YahooQuestionController()

通过这种方式,您可能有一种方法可以重写代码以提高可读性。

通常,在这种情况下,将相似的行为组合在一起可以产生更好的抽象,例如,我们可以定义一个 mixin/base class 来利用 self.controllerGoogleQuestionControllerYahooQuestionController 之间使用共享 API 等