【问题标题】:Why does .mro() on a metaclass have a different signature? `descriptor 'mro' of 'type' object needs an argument`为什么元类上的 .mro() 有不同的签名? 'type'对象的'descriptor'mro'需要一个参数`
【发布时间】:2016-03-25 08:22:00
【问题描述】:

在 Python 中的大多数类型/类上,我可以不带参数地调用 .mro()。但不适用于type 及其后代:

In [32]: type(4).mro()
Out[32]: [int, object]

In [33]: type(type(4)).mro()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-48a6f7fcd2fe> in <module>()
----> 1 type(type(4)).mro()

TypeError: descriptor 'mro' of 'type' object needs an argument

看来我可以通过type(type(4)).mro(type(4)) 得到我想要的,但为什么我不能像在其他地方一样直接调用mro()

【问题讨论】:

    标签: python metaclass method-resolution-order


    【解决方案1】:

    因为mro 是元类的一个方法,它需要一个实例——即一个类——,就像给定一个普通类C 和一个方法m 你可以调用C.m(inst) 或@ 987654325@,但您不能调用C.m(),因为它需要self 参数。

    如果你想用元类调用mrotype 本身,你可以使用type.mro(type)

    【讨论】:

    • 嗯,我明白了。但是type 也是type 的一个实例...!令人困惑。
    • 就像objecttype 是彼此的实例。这不像解释器使用type 来创建typeobject。它们都是在解释器中硬编码的“基本”类。
    • 我想另一个困惑是我相信mro 是一个类方法,因为我在课堂上调用了它。
    • 是元类的方法,不是类方法。它们都可以从类中调用,但它们并不完全相同。
    • @gerrit 是在元类中定义的类方法,不是用@classmethod() 装饰器注入到类中的类方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 2019-02-10
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多