[英]Instance is an “object”, but class is not a subclass of “object”: how is this possible?
How is it possible to have an instance of a class which is an object
, without the class being a subclass of object
? 如何让一个类的实例成为一个
object
,而不将该类作为object
的子类? here is an example: 这是一个例子:
>>> class OldStyle(): pass
>>> issubclass(OldStyle, object)
False
>>> old_style = OldStyle()
>>> isinstance(old_style, object)
True
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__
. 在Python 2中, 类型和类不是一回事,具体来说,对于旧式类,
type(obj)
与obj.__class__
不是同一个对象 。 So it is possible because instances of old-style classes are actually of a different type ( instance
) than their class: 所以它是可能的,因为旧式类的实例实际上是与它们的类不同的类型(
instance
):
>>> 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
Old style classes are declared deprecated. 声明旧样式类已弃用。 In Python 3, there are only new-style classes;
在Python 3中,只有新式类;
class A()
is equivalent to class A(object)
and your code will yield True
in both checks. class A()
等效于class A(object)
,您的代码将在两个检查中产生True
。
Take a look at this question for some more discussion: What is the difference between old style and new style classes in Python? 看一下这个问题,进行更多讨论: Python中的旧样式和新样式类有什么区别?
Everything is an object: 一切都是对象:
isinstance(123, object) # True
isinstance("green cheese", object) # True
isinstance(someOldClassObject, object) # True
isinstance(someNewClassObject, object) # True
isinstance(object, object) # True
isinstance(None, object) # True
Note that this question has essentially nothing to do with old- vs. new-style classes. 请注意,这个问题基本上与旧式和新式类无关。
isinstance(old_style, object)
being True
is simply a corollary of the fact that every value in python is an instance of object
. isinstance(old_style, object)
为True
只是python中的每个值都是object
实例的必然结果。
When you do the expression 当你做表达时
old_style = OldStyle()
It means you are instantiating the object, which old_style is an instance of the class OldStyle. 这意味着您要实例化对象,old_style是OldStyle类的实例。
Also, both evaluates to True in Python 3.2. 此外,两者都在Python 3.2中评估为True。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.