繁体   English   中英

TypeError: super(type, obj): obj 必须是类型的实例或子类型。 创建元类后调用 super 时出错

[英]TypeError: super(type, obj): obj must be an instance or subtype of type. Error when calling super after metaclass creation

假设我使用了一个库,他们的源代码是按照这个形状编写的:

class SuperLibraryDemo:
    def __init__(self, test) -> None:
        self.test = test

    def demo(self) -> str:
        return "Returning from demo method with name: %s" % self.test


class LibraryDemo(SuperLibraryDemo):
    def __init__(self, test: str = "something") -> None:
        super(LibraryDemo, self).__init__(test)
        print("At LibraryDemo __init__ method: This should have been skipped")

    def demo(self) -> None:
        super().demo()

请记住,这是一个图书馆。 我不应该根据我的需要调整它的源代码。 但是,出于此问题的LibraryDemo之外的原因,我需要在 LibraryDemo 中切换__init__方法调用的内部代码。

考虑到这个目标,我决定在元类的帮助下编写一个CustomLibraryDemo ,如下所示:

class MetaDemo(type):
    def __new__(mcs, class_name: str, bases: Tuple[Type, ...], class_dict: Dict[str, Any]):
        basis = bases[0]
        c_attrs = dict(basis.__dict__)
        prior_c_process_bases = basis.__base__
        c_attrs["__init__"] = lambda self, settings: prior_c_process_bases.__init__(self, settings)
        new_bases = types.new_class(basis.__qualname__, basis.__bases__,
                                    exec_body=lambda np: MetaDemo.populate_class_dict(np, c_attrs))
        return super(MetaDemo, mcs).__new__(mcs, class_name, (new_bases,), class_dict)

    @staticmethod
    def populate_class_dict(namespace: Dict[str, Any], attr: Dict[str, Any]) -> None:
        for key, value in attr.items():
            namespace[key] = value

class CustomLibraryDemo(LibraryDemo, metaclass=MetaDemo):
    def __init__(self, test: Optional[str] = None) -> None:
        super(CustomLibraryDemo, self).__init__(test)
        print("At CustomDemo __init__ method: This message should appear")

    def test(self) -> None:
        print("In test method at CustomLibraryDemo class: %s" % self.test)

虽然乍一看这种方法似乎对我有用,但当我调用CustomLibraryDemo().demo()时出现错误:

TypeError: super(type, obj): obj must be an instance or subtype of type

为什么?

您可能不需要自定义元类; 相反,只需将 arguments 调整为super

class CustomLibraryDemo(LibraryDemo):
    def __init__(self, test: Optional[str] = None) -> None:
        super(LibraryDemo, self).__init__(test)
        print("At CustomDemo __init__ method: This message should appear")

    def test(self) -> None:
        print("In test method at CustomLibraryDemo class: %s" % self.test)

在决定下一步使用哪个 class 时,使用LibraryDemo而不是CustomerLibraryDemo会导致super沿着 MRO 进一步启动。

% python3 tmp.py
At CustomDemo __init__ method: This message should appear

这个问题解决了我的问题。 就我而言,在bases方法签名上__new__ basis.__bases__参数可以解决问题。 这样, new_bases变量的语法变成:

new_bases = types.new_class(basis.__qualname__, bases,
                                    exec_body=lambda np: MetaDemo.populate_class_dict(np, c_attrs))

顺便说一句,这段代码可以简化为:

new_bases = type(basis.__qualname__, bases, c_attrs)

删除populate_class_dict元类方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM