子类的元类是如何确定的?
对于下面的代码:
class TestMeta(type):
def __init__(cls, classname, bases, dict_):
print(f'In TestMeta, class {cls}')
type.__init__(cls, classname, bases, dict_)
class Parent(metaclass=TestMeta):
pass
class Child(Parent, metaclass=type):
pass
输出是:
In TestMeta, class <class '__main__.Parent'>
In TestMeta, class <class '__main__.Child'>
在我看来,在创建类 Parent
时,TestMeta.__init__
会运行,但是为什么在创建类时又运行>Child
我已将其元类更改为 type
?继承和传递元类
时,元类是如何确定的?
For the code below:
class TestMeta(type):
def __init__(cls, classname, bases, dict_):
print(f'In TestMeta, class {cls}')
type.__init__(cls, classname, bases, dict_)
class Parent(metaclass=TestMeta):
pass
class Child(Parent, metaclass=type):
pass
The output is:
In TestMeta, class <class '__main__.Parent'>
In TestMeta, class <class '__main__.Child'>
In my opinion, when creating the class Parent
, TestMeta.__init__
will run, but why it runs again when creating the class Child
which I have changed its metaclass as type
? How is the metaclass determined when inheriting and passing a metaclass
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自文档:
在上面的例子中,第三个项目符号成立,因为
type
被作为显式元类给出,并且存在基类。根据最派生元类的定义,候选者是:
TestMeta
和type
。由于TestMeta
继承了type
,因此它是最派生的元类,并且确实是Child
的元类。为了演示差异,以下代码展示了我们如何“强制”
Child
获取指定的元类
而不是继承的元类: 。
再次注意,根据最派生元类的定义,只有当
OtherMeta
本身是TestMeta
的子类时,这才有效 删除这个继承关系会报错:From the docs:
In your case above, the third bullet holds, as
type
is given as the explicit metaclass and there are base-classes.According to the definition of the most derived metaclass, the candidates are:
TestMeta
andtype
. SinceTestMeta
inheritstype
, it is the most derived metaclass and is indeed the metaclass ofChild
.To demonstrate the difference, the following code shows how we can "force"
Child
to get the specifiedmetaclass
instead of the inherited one:The output would be:
Notice that again, according to the definition of the most derived metaclass, this only works if
OtherMeta
itself is a subclass ofTestMeta
. Removing this inheritance relation will give the error: