【问题标题】:Defining classes with and without (object) [duplicate]定义有和没有(对象)的类[重复]
【发布时间】:2016-01-15 04:28:11
【问题描述】:

我正在尝试学习 Python 3。在我读的一本书中,定义一个你使用的类:

class Classname:
    # and so on

在另一个上面写着:

class Classname(object):
    # and so on

哪种方法是正确的?它们有何不同?

【问题讨论】:

    标签: python class python-3.x


    【解决方案1】:

    只有 python 2.7 有区别:old-style and new-style classes in Python 2.7?

    在python 3中

    class SomeClass:
        ...
    

    一样
    class SomeClass(object):
        ...
    

    【讨论】:

      【解决方案2】:

      在您提到的特定情况下(即从 object 继承),这在 Python 3 中没有区别。在 Python 2 中,这是旧样式类之间的区别

      class Classname:
          ...
      

      和新的样式类

      class Classname(object):
          ...
      

      其行为与 herehere 所述不同。

      当您使用 Python 3 进行编程时,我将省略它以使您的代码更易于阅读。由于所有对象都隐式继承自 object,因此此信息对阅读您的代码没有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-15
        • 2022-01-25
        • 2017-02-20
        • 2013-01-01
        • 2021-07-30
        • 2021-09-20
        • 2019-01-06
        • 2019-08-22
        相关资源
        最近更新 更多