python - 为什么从对象继承在 Python 中有所不同?

标签 python object inheritance

<分区>

当类从无继承时,我有一个实例类型的对象。

>>> 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 中,旧式类已被删除。

关于python - 为什么从对象继承在 Python 中有所不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18345827/

相关文章:

Python 复制特定行和列并更新现有模板文件

java - 理解Java中的层次结构

c++ - 如何为子函数指定模板参数?

python - 在字典中存储多个图像文件

Python 从 url 逐行下载大型 csv 文件,只有 10 个条目

python - 如何在Python中读取多行JSON文件并统计特定字段的单词数

c# - 带参数的 void 方法和不带参数的返回值方法?

java - 如何使用定义的对象作为输入变量?

python - 如何在 Python 中创建对象集合代理?

java - 需要帮助编译此迭代和接口(interface)程序