【发布时间】:2018-03-13 05:13:58
【问题描述】:
是否有任何不是 type 元类实例的内置 Python 类?
>>> type(list)
<type 'type'>
>>> type(dict)
<type 'type'>
>>> type(some_builtin_python_class)
<type 'some_type_other_than_type'>
【问题讨论】:
是否有任何不是 type 元类实例的内置 Python 类?
>>> type(list)
<type 'type'>
>>> type(dict)
<type 'type'>
>>> type(some_builtin_python_class)
<type 'some_type_other_than_type'>
【问题讨论】:
取决于您所说的“内置”是什么意思。如果您的意思是任何 C 实现的(在 CPython 中)类公开为内置函数(以及在 builtin 中),那么不,它们都没有不同的元类。*
但在标准库中肯定有类可以做到。例如:
>>> type(collections.abc.Iterable)
abc.ABCMeta
澄清一下:其他元类当然是类型的子类,因此,按照正常的继承规则,isinstance(Iterable, type) 仍然是真的——但type(Iterable) == type 不是真的。这就是您在问题中所要求的——type(T) 返回<type 'some_type_other_than_type'> 的类型。
* 无论如何,不在 3.x 中。在 2.x 中情况有所不同,其中有经典类,并且曾几何时,“假类”实际上是看起来像 type 实例但实际上不是的函数,并返回隐藏的 type 实例调用时的实例。
【讨论】:
builtin 模块。无论如何,你是对的,这个模块中没有这样的类。我有just checked it
inspect,因为我想在 2.4 上运行它,但后来我找不到我的工作 2.4 安装,所以这一切都是浪费...... :)
isinstance(collections.abc.Iterable, type) 是 True。
type 的子类,因此具有自定义元类的类是type 的实例。但这只是正常的继承;我猜他的意思是type(x) == type,而不是instance(x, type)。
type(Iterable).__mro__ 产生 (abc.ABCMeta, type, object)