实例是“对象",但类不是“对象"的子类:这怎么可能? [英] Instance is an "object", but class is not a subclass of "object": how is this possible?
问题描述
如何有一个类为object
的实例,而该类不是object
的子类呢?这是一个例子:
How is it possible to have an instance of a class which is an object
, without the class being a subclass of object
? here is an example:
>>> class OldStyle(): pass
>>> issubclass(OldStyle, object)
False
>>> old_style = OldStyle()
>>> isinstance(old_style, object)
True
推荐答案
在Python 2中, type 和 class 不同,特别是对于旧样式类,type(obj)
与obj.__class__
不同的对象 .因此这是可能的,因为老式类的实例实际上是与其类不同的类型(instance
):
In Python 2, type and class are not the same thing, specifically, for old-style classes, type(obj)
is not the same object as obj.__class__
. So it is possible because instances of old-style classes are actually of a different type (instance
) than their class:
>>> class A(): pass
>>> class B(A): pass
>>> b = B()
>>> assert b.__class__ is B
>>> issubclass(b.__class__, A) # same as issubclass(B, A)
True
>>> issubclass(type(b), A)
False
>>> type(b)
<type 'instance'>
>>> b.__class__
<class __main__.B at 0x10043aa10>
这在新式的类中得到解决:
This is resolved in new-style classes:
>>> class NA(object): pass
>>> class NB(NA): pass
>>> nb = NB()
>>> issubclass(type(nb), NA)
True
>>> type(nb)
<class '__main__.NB'>
>>> nb.__class__
<class '__main__.NB'>
旧类不是类型,新类是:
Old-style class is not a type, new-style class is:
>>> isinstance(A, type)
False
>>> isinstance(NA, type)
True
旧样式类被声明为已弃用.在Python 3中,只有新型类. class A()
等同于class A(object)
,并且您的代码在两次检查中都将产生True
.
Old style classes are declared deprecated. In Python 3, there are only new-style classes; class A()
is equivalent to class A(object)
and your code will yield True
in both checks.
请看以下问题进行更多讨论:什么是python中旧样式类与新样式类之间的区别?
Take a look at this question for some more discussion: What is the difference between old style and new style classes in Python?
这篇关于实例是“对象",但类不是“对象"的子类:这怎么可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!