Home >Backend Development >Python Tutorial >python的type和object之间是怎么一种关系?
是初学者请勿喷啊
两个是互为实例的关系,但不是互为子类的关系,只有type是object的子类,反之则不成立。大牛说两者是蛋生鸡鸡生蛋的关系,但我还是不明白,有懂的麻烦解释一下,希望不要给出外文的链接。python为什么设计出两个,去掉 一个行不行?
<code class="language-text">#define PyVarObject_HEAD_INIT(type, size) \
1, type, size,
PyTypeObject PyType_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"type", /* tp_name */
sizeof(PyHeapTypeObject), /* tp_basicsize */
sizeof(PyMemberDef), /* tp_itemsize */
0, /* tp_base */
...
}
</code>
谢邀,object是type(object的类型是type),type也是object(type继承自object)<code class="language-python"><span class="o">>>></span> <span class="nb">isinstance</span><span class="p">(</span><span class="nb">object</span><span class="p">,</span> <span class="nb">type</span><span class="p">)</span>
<span class="bp">True</span>
<span class="o">>>></span> <span class="nb">isinstance</span><span class="p">(</span><span class="nb">type</span><span class="p">,</span> <span class="nb">object</span><span class="p">)</span>
<span class="bp">True</span>
</code>
这部分我当初是读MSDN里关于C Sharp的Object 和 type 的关系读懂的……你如果手边有Jeffery的《CLR via C#》 可以读一下。专门为了这个问题去买一本可能有点奢侈,不过如果你是 .net 程序员,我推荐你收一本。<code class="language-c"><span class="cm">/* PyObject_HEAD defines the initial segment of every PyObject. */</span>
<span class="cp">#define PyObject_HEAD \</span>
<span class="cp"> _PyObject_HEAD_EXTRA \</span>
<span class="cp"> Py_ssize_t ob_refcnt; \</span>
<span class="cp"> struct _typeobject *ob_type;</span>
</code>
既不是互为实例:<code class="language-text">class C(object):
a = 1
def f(self):
pass
c = C()
c.f() # 行为由C决定
C.a # 行为由type决定
</code>
之前读过一篇讨论这个问题文章,链接已经丢了。。。建议题主读一读《Ruby元编程》,这本书对类和对象有较清晰和深入的讨论,要求不高,Ruby和Python的对象模型非常相似,不懂Ruby也能读懂。<code class="language-python"><span class="o">>>></span> <span class="n">B</span><span class="o">.</span><span class="n">__base__</span>
<span class="o"><span class="k">class</span> <span class="err">'</span><span class="nc">A</span><span class="s">'></span>
</span></code>