Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

python - 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? here is an example:

>>> class OldStyle(): pass
>>> issubclass(OldStyle, object)
False
>>> old_style = OldStyle()
>>> isinstance(old_style, object)
True
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

Take a look at this question for some more discussion: What is the difference between old style and new style classes in Python?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...