python - 长类名的最佳命名约定是什么?

标签 python model-view-controller flask conventions pep8

现在,我正在将 Python-flask 代码编写为 MVC 模式。 但是,我认为我自己,我认为 Controller 类的声明符太长

例如我有

class GoogleQuestionController:
    def __init__(self):

        (.....)

class YahooQuestionController:
    def __init__(self):

        (.....)

两个非常相似的类名,所以我无法定义像这样的声明符

question_controller = GoogleQuestionController()

同上。

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

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()

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

google = GoogleQuestionController()
yahoo = YahooQuestionController()

同样,如果动词没有歧义,例如如果我在 Google 对象/模块内,我会使用 question (或者可能是 controller):

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

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

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

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

关于python - 长类名的最佳命名约定是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47087202/

相关文章:

flask - Sqlalchemy - 当数据有关系时如何正确地将数据批量插入到数据库中

python - 最Pythonic的方式来中止缓存装饰器?

python - 尝试在 Django 中遍历 session 字典时出现 KeyError 0

Python 类返回类型

java - 命令行上的 MVC

java - Model 1 是 MVC 架构的子类吗?

python - 在 Pandas 数据框中对重复的列 ID 进行分组

python - 如何解决 python axelrod Lookerup 策略中的关键错误

ruby-on-rails - 在不同的 Controller 中使用 Shopify API

python - Flask jsonify 对象列表