您必须创建第二个元类,继承自您的原始元类和 abc.ABCMeta,并将该元类用作所需类的元类。
如果您的元类构造正确,在它实现的所有(特殊)方法中使用 super() 调用,它就像这样简单:
import abc
...
class KindMeta(type):
...
class CombinedMeta(KindMeta, abc.ABCMeta):
pass
class Kind(ABC, metaclass=CombinedMeta):
...
如果您的元类没有使用super(),而是调用硬编码的type 方法,您必须更改它才能这样做。对于像__prepare__和__call__这样的一些方法,不给通讯员打电话是有意义的
super() 方法取决于你在做什么,我认为没有必要运行ABCMeta 中的对应方法。
而且,当然,只有在您不想或无法更改已有的元类,或者如果您希望您的元类用于其他不使用 ABC 的类时,才需要这样做 -
否则,您可以让自己的元类继承自 ABCMeta 本身 - 无需创建第三个元类来组合两者:
import abc
...
class KindMeta(abc.ABCMeta):
...
另一方面,如果您使用 Python 的元类 + 类构造机制来创建“不完全是类”的对象(例如 zope.interface 包创建接口),您必须决定(1)如果在abc.ABC 中使用它是否有意义,其次,如果必须运行 ABCMeta 中的对应方法(通常是的,如果您需要该功能)。在这种情况下,您必须适当地自定义您的元类 - 这可能包括强制将类与多重继承组合(即使您可以仅从 ABCMeta 继承)以防止它调用type.__new__(如果这是您的意图):
class KindMeta(type):
def __new__(mcls, name, bases, ns, **kw):
cls = ExistingClassRegistry[name]
return cls
class CombinedMeta(abc.ABCMeta, KindMeta):
# note the reversed order - ABCMeta will run first
# and call super().__new__ which runs KindMeta.__new__ and
# does not forward to type.__new__
pass