首页 > Python type(type)得到的为什么是<type 'type'>

Python type(type)得到的为什么是<type 'type'>

IDLE Python shell 2.7.9


因为 type 是 type 类的实例呗。

难道你以为 type 是函数啊?不是的,int、str、bytes、list 等等,虽然平时会把它们当函数用,但其实它们都是类。而 Python 里绝大部分类都是 type 这个元类的实例(元类也是类,并且 type 也是以 type 为元类的类,即 type 是 type 的实例)。另外一小部分类不是 type 的实例也极有可能是 type 的子类的实例(如 enum.Enum)。我到目前为止还没有见过例外(当然为此目的构造的类不算)。

关于 Python 中的元类的信息可以参阅这个文档:https://docs.python.org/3/reference/datamodel.html#metaclasses

当然,我在此忽略了 Python 2 中的旧式类。


type是Python中的元类,可以用来创建其他类。。int, long, list, dict, tuple这些内置类型都是type的实例。。type也是由type创建,所以type(type)的结果是type。。
没明白的话,建议你看一下Python中的元类,http://xianglong.me/article/learn-python-7-python-metaclass/

【热门文章】
【热门文章】