繁体   English   中英

为什么您不必为在 python 中只有 __init__ 的 class 声明(对象)?

[英]Why is it that you don't have to declare (object) for a class that only has __init__ in python?

感谢您帮助 n00b

我正在谈论的示例:

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

为什么当你声明class时,你不必向它添加(对象),

class Complex(object):

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

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

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__']

When you define the class simply like this class Complex you don't inherit the class from any other class and hence it only has those attributes which you define like __init__ (and __doc__ and __module__ .) This is a an old-style class.

When you define a class like this - class Complex(object) , it means you inherit the class from the class object . 因此,它的许多属性都是自动继承的,而无需像__str____class__等自己再次定义它们。这是新样式class。

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

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

(另外,根据您所说,从object继承与仅定义__init__无关。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM