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__)
但是如果你问的是对象和类型之间的奇怪关系:
>>> isinstance(object, object)
True
>>> isinstance(type, type)
True
>>> isinstance(object, type)
True
>>> isinstance(type, object)
True
这更像是鸡与蛋的问题:哪个先出现?
答案是PyObject,它用C语言定义.
在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
print(isinstance(TYPE,OBJECT))
print(isinstance(OBJECT,TYPE))
print(isinstance(TYPE,TYPE))
print(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编写的源代码.