【问题标题】:Built-in classes metaclass in PythonPython中的内置类元类
【发布时间】: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'>

【问题讨论】:

    标签: python metaclass


    【解决方案1】:

    取决于您所说的“内置”是什么意思。如果您的意思是任何 C 实现的(在 CPython 中)类公开为内置函数(以及在 builtin 中),那么不,它们都没有不同的元类。*

    但在标准库中肯定有类可以做到。例如:

    >>> type(collections.abc.Iterable)
    abc.ABCMeta
    

    澄清一下:其他元类当然是类型的子类,因此,按照正常的继承规则,isinstance(Iterable, type) 仍然是真的——但type(Iterable) == type 不是真的。这就是您在问题中所要求的——type(T) 返回&lt;type 'some_type_other_than_type'&gt; 的类型。


    * 无论如何,不​​在 3.x 中。在 2.x 中情况有所不同,其中有经典类,并且曾几何时,“假类”实际上是看起来像 type 实例但实际上不是的函数,并返回隐藏的 type 实例调用时的实例。

    【讨论】:

    • 谢谢!我的意思是 python 中的builtin 模块。无论如何,你是对的,这个模块中没有这样的类。我有just checked it
    • @IvanKalita:比我自己的支票干净得多。我没有使用inspect,因为我想在 2.4 上运行它,但后来我找不到我的工作 2.4 安装,所以这一切都是浪费...... :)
    • 虽然即使是 collections.abc.Iterable 也是一个类型的实例。 isinstance(collections.abc.Iterable, type)True
    • @OlivierMelançon 当然——元类是type 的子类,因此具有自定义元类的类是type 的实例。但这只是正常的继承;我猜他的意思是type(x) == type,而不是instance(x, type)
    • 这个答案完全不正确,因为 stdlib 中的其他元类也是类型的后代:type(Iterable).__mro__ 产生 (abc.ABCMeta, type, object)
    猜你喜欢
    • 2012-03-26
    • 2011-10-21
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多