我正在通读 this blog ,其中包含:
Since in Python everything is an object, everything is the instance of a class, even classes. Well, type is the class that is instanced to get classes. So remember this: object is the base of every object, type is the class of every type. Sounds puzzling? It is not your fault, don't worry. However, just to strike you with the finishing move, this is what Python is built on.
>>> type(object)
<class 'type'>
>>> type.__bases__
(<class 'object'>,)
我无法理解这一点。任何人都可以用不同的方式解释这种关系以使其更清楚吗?
最佳答案
type(x)
的关系和x.__class__
的结果基本一样:
for obj in (object,type,1,str):
assert type(obj) is obj.__class__
print("type(obj) and obj.__class__ gave the same results in all test cases")
__bases__
表示派生类的基础:
class parent:
pass
class child(parent,int):
pass
print(child.__bases__) # prints (<class '__main__.parent'>, <class 'int'>)
但是,如果您询问 object
和 type
之间的奇怪关系:
# are `object` and `type` both instances of the `object` class?
>>> isinstance(object, object) and isinstance(type, object)
True
# are they also instances of the `type` class?
>>> isinstance(object, type) and isinstance(type, type)
True
# `type` is a subclass of `object` and not the other way around (this makes sense)
>>> [issubclass(type, object), issubclass(object, type)]
[True, False]
这更像是先有鸡还是先有蛋的问题:哪个先出现?
答案是用C定义的PyObject
在 object
或 type
可用于 python 解释器之前,它们的底层机制是在 C 中定义的,并且实例检查在它们被定义后被覆盖。 (表现得像抽象类,参见 PEP 3119 )
你可以把它看成是这样的 python 实现:
#this wouldn't be available in python
class superTYPE(type):
def __instancecheck__(cls,inst):
if inst ==TYPE:
return True
else:
return NotImplemented #for this demo
class TYPE(type,metaclass=superTYPE):
def __instancecheck__(cls,inst):
if inst in (OBJECT,TYPE):
return True
else:
return NotImplemented #for this demo
class OBJECT(metaclass=TYPE):
pass
# these all pass
assert isinstance(TYPE,OBJECT)
assert isinstance(OBJECT,TYPE)
assert isinstance(TYPE,TYPE)
assert isinstance(OBJECT,OBJECT)
实际上它可能更好地表示为:
#this isn't available in python
class superTYPE(type):
def __instancecheck__(cls,inst):
if inst in (TYPE,OBJECT):
return True
else:
return NotImplemented #for this demo
class OBJECT(metaclass=superTYPE):
pass
class TYPE(OBJECT):
pass
但是如果您想确切地知道它是如何工作的,您需要查看用 C 编写的源代码。
关于python - python中类型与对象的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36339553/