【问题标题】:What is the preferred Python 3.x class definition syntax? [closed]首选的 Python 3.x 类定义语法是什么? [关闭]
【发布时间】:2014-01-14 16:40:23
【问题描述】:

正如Is it necessary or useful to inherit from python's object in Python 3.x?Python class inherits object 明确指出的那样,在Python 3 中定义类时,不再需要object 继承。

作为一个推论,这两个问题都没有直接解决:在编写新的 Python 3 代码时,我是否应该更喜欢其中一种风格?为了更清晰的类定义而放弃object 基类,还是保留它以便(可能)使未来的Python 2 移植更容易?

【问题讨论】:

    标签: python class python-3.x coding-style new-style-class


    【解决方案1】:

    编程正在将抽象概念转换为正式形式,然后用于生成可执行文件。没有必要使过程比必要的复杂。这些机器是为了帮助我们而创造的。它不适用于相反的方向。

    在某种意义上,Python 3 一门新语言。那么问题应该是:“我应该强迫自己使用新语言,让它看起来像旧工具/程序员习惯的样子吗?”

    又到了一一读Python之禅的时候了:

    >>> import this
    The Zen of Python, by Tim Peters
    
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
    

    【讨论】:

      【解决方案2】:

      pylint 在 3.x 中定义类时似乎仍然警告不要使用对象,所以我也添加了它,即使对于 3.x-only 代码也是如此。我写了很多在 2.x 和 3.x 上运行的 Python;这就是你想要的小菜一碟。

      但你为双方都提出了合理的论据,真的。 怎么想?

      【讨论】:

      • 我认为没有它会更干净。但如果存在这样的事情,我真的在寻找“标准公认的做法”。
      • 公认的标准做法曾经是在火中磨尖长矛,以便更轻松地杀死洞穴熊。源代码只是源代码。它没有被切割成石头。如有必要,可以稍后更改。
      猜你喜欢
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 2010-11-09
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      相关资源
      最近更新 更多