如何在 python 中定义抽象元类
How to define an abstract metaclass in python
在python中定义抽象元class并像这样实例化它时:
from abc import ABC, abstractmethod
class AbstractMetaClass(type, ABC):
@abstractmethod
def func(self):
pass
class MyClass(metaclass=AbstractMetaClass):
pass
我原以为我的代码会失败,因为 MyClass 是抽象 class 的一个实例。相反,它运行没有问题。
发生了什么事,我该怎么做?
好吧,您只是发现它不起作用。你在想什么是有道理的:也许它应该失败。只是 abstract 类 并非设计为作为 meta类 工作,而是与“type”协同工作。我实际上觉得不可思议,因为大多数 Python 对象机制在与 meta类 一起使用时恰好“正常工作”——包括 properties
、特殊的双打方法,如 __getitem__
和运算符方法等等在。你刚刚碰到了一个碰巧不起作用的东西。
如果您的设计确实有意义,您可能只想在“抽象元类”__init__
方法上手动检查抽象方法:
from abc import classmethod
class AbstractMetaClass(type):
def __init__(cls, name, bases, ns, **kwargs):
for meth_name, meth in cls.__class__.__dict__.items():
if getattr(meth, "__isabstractmethod__", False):
raise TypeError(f"Can't create new class {name} with no abstract classmethod {meth_name} redefined in the metaclass")
return super().__init__(name, bases, ns, **kwargs)
@abstractmethod
def func(cls):
pass
请注意,为清楚起见,元类上的普通方法最好将“cls”作为第一个参数而不是“self”(尽管这可能是个人喜好)
在python中定义抽象元class并像这样实例化它时:
from abc import ABC, abstractmethod
class AbstractMetaClass(type, ABC):
@abstractmethod
def func(self):
pass
class MyClass(metaclass=AbstractMetaClass):
pass
我原以为我的代码会失败,因为 MyClass 是抽象 class 的一个实例。相反,它运行没有问题。 发生了什么事,我该怎么做?
好吧,您只是发现它不起作用。你在想什么是有道理的:也许它应该失败。只是 abstract 类 并非设计为作为 meta类 工作,而是与“type”协同工作。我实际上觉得不可思议,因为大多数 Python 对象机制在与 meta类 一起使用时恰好“正常工作”——包括 properties
、特殊的双打方法,如 __getitem__
和运算符方法等等在。你刚刚碰到了一个碰巧不起作用的东西。
如果您的设计确实有意义,您可能只想在“抽象元类”__init__
方法上手动检查抽象方法:
from abc import classmethod
class AbstractMetaClass(type):
def __init__(cls, name, bases, ns, **kwargs):
for meth_name, meth in cls.__class__.__dict__.items():
if getattr(meth, "__isabstractmethod__", False):
raise TypeError(f"Can't create new class {name} with no abstract classmethod {meth_name} redefined in the metaclass")
return super().__init__(name, bases, ns, **kwargs)
@abstractmethod
def func(cls):
pass
请注意,为清楚起见,元类上的普通方法最好将“cls”作为第一个参数而不是“self”(尽管这可能是个人喜好)