当前位置 : 主页 > 手机开发 > 其它 >

为什么从对象继承会在Python中产生影响?

来源:互联网 收集:自由互联 发布时间:2021-06-19
参见英文答案 Python class inherits object6个 当类从没有继承时,我有一个实例类型的对象. class A(): pass; a = A() type(a)type 'instance' type(a) is AFalse type(A)type 'classobj' 但是,当我从对象继承相同的类时
参见英文答案 > Python class inherits object                                    6个
当类从没有继承时,我有一个实例类型的对象.

>>> class A(): pass;
>>> a = A()
>>> type(a)
<type 'instance'>
>>> type(a) is A
False
>>> type(A)
<type 'classobj'>

但是,当我从对象继承相同的类时,创建的对象是A的类型.

>>> class A(object): pass;
>>> a = A()
>>> type(a)
<class '__main__.A'>
>>> type(a) is A
True
>>> type(A)
<type 'type'>

这背后的逻辑是什么?这是否意味着每个类都应该从对象继承?

在Python 3中,这两个是相同的.但是,在Python 2中:

class A: pass  # old-style class

class B(object): pass  # new-style class

从文档中的New-style and classic classes开始:

Up to Python 2.1, old-style classes were the only flavour available to the user. The concept of (old-style) class is unrelated to the concept of type: if x is an instance of an old-style class, then x.__class__ designates the class of x, but type(x) is always <type 'instance'>. This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance.

New-style classes were introduced in Python 2.2 to unify classes and types. A new-style class is neither more nor less than a user-defined type. If x is an instance of a new-style class, then type(x) is the same as x.__class__.

The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model. It also has a number of immediate benefits, like the ability to subclass most built-in types, or the introduction of “descriptors”, which enable computed properties.

出于这些原因,尽可能使用新式课程是个好主意.旧式类甚至存在于Python 2.2中的唯一原因是为了向后兼容;在Python 3中,删除了旧式类.

网友评论