python 3 : How can object be instance of type?

标签 python python-3.x python-3.4

在 Python 3 中,objecttype 的实例,type 也是 object 的实例!

为什么每个类都派生自另一个类?

任何实现细节?

我使用 isinstance(sub, base) 检查了这一点,根据 Python 文档,它检查子类是否派生自基类:

isinstance(object, type)
Out[1]: True

isinstance(type, object)
Out[2]: True

最佳答案

这是 Python 中的一种边缘情况:

  • Python 中的一切都是对象,因此由于 object 是一切的基本类型,type(在 Python 中是某种东西)是 object< 的一个实例
  • 因为 object 是一切的基础 typeobject 也是一个 type,这使得 object type 的实例。

请注意,这种关系不是您可以在 Python 中用您自己的东西复制的。这是语言中内置的一个异常。


在实现方面,这两个名称分别由PyBaseObject_Type(代表object)和PyType_Type(代表type).

当你使用 isinstance 时,类型检查——在最后一步,在其他一切都失败之后——由 type_is_subtype_base_chain 完成。 :

type_is_subtype_base_chain(PyTypeObject *a, PyTypeObject *b)
{
    do {
        if (a == b)
            return 1;
        a = a->tp_base;
    } while (a != NULL);

    return (b == &PyBaseObject_Type);
}

这实质上是在 a 的类型层次结构中向上移动,并根据 b 检查结果类型。如果找不到,那么最后的手段是检查 b 是否实际上是 object,在这种情况下函数返回 true:因为一切都是对象。因此,“一切都是 object 的实例”部分实际上被硬编码到实例检查中。

至于为什么object是一个类型,其实更简单,因为它在declaration of PyBaseObject_Type中就是这么定义的:

PyTypeObject PyBaseObject_Type = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "object",                                   /* tp_name */
    sizeof(PyObject),                           /* tp_basicsize */
    …

PyVarObject_HEAD_INIT 本质上设置了核心类型信息,包括基本类型,即 PyType_Type

这种关系其实还有两个后果:

  • 因为一切都是对象,object 也是 object 的一个实例:isinstance(object, object)
  • 由于 PyType_Type 也是使用相同的 PyVarObject_HEAD_INIT 实现的,type 也是一种类型:isinstance(type, type)

关于 python 3 : How can object be instance of type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31995472/

相关文章:

python - 读取输入后隐藏控制台窗口

python - 两次分配变量?

python - 带有 Python 3 的 opencv 3.0.0 alpha 无法导入 cv2

python - 使用 gpu 使用 opencv 测量图像清晰度

python - Snakemake Expand+zip 函数意外行为

python-3.x - 谷歌云存储、计算引擎和权限不足错误

r - 使用 pip 为 Python 3 安装 rpy2

python - 代码到 def 函数中

python - 使用自定义 url_path 在 @list_route 上反转

python - 通过 importlib 以编程方式导入模块 - __path__ 未设置?