【问题标题】:Why is it that you don't have to declare (object) for a class that only has __init__ in python? [duplicate]为什么你不必为在 python 中只有 __init__ 的类声明(对象)? [复制]
【发布时间】:2011-07-18 06:03:43
【问题描述】:

感谢您对 n00b 的帮助

我所说的例子:

class Complex:
    def __init__(self,x,y):
        self.x = x
        self.y = y

为什么在声明类的时候不用添加(对象)呢,

class Complex(object):

【问题讨论】:

标签: python oop class object


【解决方案1】:
class Complex1:
    def __init__(self,x,y):
        self.x = x
        self.y = y

>>> dir(Complex1)
['__doc__', '__init__', '__module__']    

class Complex2(object):
    def __init__(self,x,y):
        self.x = x
        self.y = y

>>> dir(Complex2)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__']

【讨论】:

    【解决方案2】:

    在 Python 2.x 中,这使您的类 old-style 具有不同的继承语义。由于您不使用继承(并且在简单情况下方法解析顺序相同),因此在实践中没有区别。如果您使用 Python 2.x 进行编程,则应添加 (object) 以从新型类的优势中获益。

    在 Python 3.2 中,object 只是您继承自的默认类,可以省略。

    【讨论】:

      【解决方案3】:

      当您像 class Complex 这样简单地定义类时,您不会从任何其他类继承该类,因此它只有您定义的那些属性,例如 __init__(以及 __doc____module__。)这是一个老式类。

      当您定义这样的类 - class Complex(object) 时,这意味着您从类 object 继承该类。因此,它的许多属性都是自动继承的,而无需像__str____class__ 等自己重新定义它们。这是新样式类。

      在 python 2.x 中,通常首选新样式类,因为使用旧样式类可能会导致一些问题。例如,__slots__superdescriptors 不适用于旧式类。

      python 2.x 中保留了旧样式类,只是为了保持向后兼容性。在 python 3 中,这被清理了,您定义的任何类都是新样式类。

      (另外,根据你的说法,从object继承与只定义__init__无关。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-05
        • 1970-01-01
        • 2019-11-15
        • 1970-01-01
        • 1970-01-01
        • 2015-12-27
        • 1970-01-01
        相关资源
        最近更新 更多