子类继承type时触发TypeError: metaclass conflict问题求助
问题原因
触发元类冲突的核心逻辑是:
Class_Foo是通过SubType创建的类,因此它的元类是SubType;Class_Foo的基类是MyABC,而MyABC的元类是ABCMeta;- Python的规则是:派生类的元类必须是其所有基类元类的(非严格)子类。但
SubType直接继承自type,和ABCMeta是平级关系(二者都继承自type),不存在继承关系,因此触发了冲突。
你之前的误解是认为“实例不会触发元类冲突”,但这里的实例本身是一个类,它作为派生类,必须遵守基类的元类规则。
修复方案
让SubType继承自ABCMeta而非type即可解决问题——因为ABCMeta本身就是type的子类,这样SubType就成为了ABCMeta的子类,完全符合Python对派生类元类的要求。
修改后的完整代码:
from abc import ABCMeta, abstractmethod class MyABC(metaclass=ABCMeta): @abstractmethod def some_abstract_method(self): raise NotImplementedError def some_mixin_method(self): print('some_mixin_method()') self.some_abstract_method() # 将SubType的父类从type改为ABCMeta class SubType(ABCMeta): _types = dict() def __new__(cls, string): if string in cls._types: self = cls._types[string] else: name = f'Class_{string}' bases = (MyABC,) dict_ = { 'string': string, 'some_abstract_method': cls._some_abstract_method } self = super(SubType, cls).__new__(cls, name, bases, dict_) cls._types[string] = self return self @staticmethod def _some_abstract_method(self): print('some_abstract_method()') print(f'string: {self.string}') # 测试代码 Class_Foo = SubType('Foo') obj = Class_Foo() obj.some_mixin_method()
运行后会输出:
some_mixin_method() some_abstract_method() string: Foo
内容的提问来源于stack exchange,提问作者Prown
相关产品推荐
相关产品推荐

