在元类中实例化justcreated类会导致RuntimeError(“super():empty\uuu class\uuCell”)

2024-10-01 02:32:04 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个元类,我想用它来自动注册新的组件,也就是一些基本组件类的子类。注册新组件时,它的实例将被传递到处理该组件的register_component()函数。在

元类代码(精简版):

class AutoRegisteredMeta(type):
    def __new__(metacls, name, bases, attrs):

        # ... (omitted) check if "name" has already been registered ...

        new_class = super().__new__(metacls, name, bases, attrs)
        register_component(name, new_class())  # RuntimeError(super(): empty __class__ cell)
        return new_class

问题是,调用new_class()会导致错误,但并非所有类都会出现错误。经过一些实验后,我意识到只有当一个子类在它自己的__init__()方法中调用super().__init__()时才会发生这种情况。在

示例组件和基类:

^{pr2}$

我做错什么了?阅读this我发现我可能不应该在元类的__new__()或{}中进行实例化,对吗?这也许能被规避吗?在

另外,用外行的话来解释也不错,我不太了解CPython实现的内部结构。在

提前谢谢!在

(FWIW,我使用python3.3.6,Ubuntu)


编辑:我正在添加请求的最小示例,您可以直接运行它,并亲自查看操作中的错误。

#!/usr/bin/env python3


class AutoRegisteredMeta(type):
    def __new__(metacls, name, bases, attrs):
        new_class = super().__new__(metacls, name, bases, attrs)
        new_class()  # <--- RuntimeError can occur here
        return new_class


class BaseComponent(metaclass=AutoRegisteredMeta):
    def __init__(self):
        print("BaseComponent __init__()")


class GoodComponent(BaseComponent):
    def __init__(self):
        print("GoodComponent __init__()")


class BadComponent(BaseComponent):
    def __init__(self):
        print("BadComponent __init__()")
        super().__init__()  # <--- RuntimeError occurs because of this

Tags: nameselfnewinitdef错误组件attrs
1条回答
网友
1楼 · 发布于 2024-10-01 02:32:04

也许这是可行的:

#!/usr/bin/env python3


class AutoRegisteredMeta(type):
    def __new__(metacls, name, bases, attrs):
        new_class = super().__new__(metacls, name, bases, attrs)
        new_class()
        return new_class


class BaseComponent(metaclass=AutoRegisteredMeta):
    def __init__(self):
        print("BaseComponent __init__()")


class GoodComponent(BaseComponent):
    def __init__(self):
        print("GoodComponent __init__()")


class BadComponent(BaseComponent):
    def __init__(self):
        print("BadComponent __init__()")
        super(self.__class__, self).__init__()

相关问题 更多 >