python - 如何在python中定义一个抽象元类
问题描述
在 python 中定义抽象元类并像这样实例化它时:
from abc import ABC, abstractmethod
class AbstractMetaClass(type, ABC):
@abstractmethod
def func(self):
pass
class MyClass(metaclass=AbstractMetaClass):
pass
我原以为我的代码会失败,因为 MyClass 是抽象类的一个实例。相反,它运行没有问题。发生了什么,我该怎么做?
解决方案
好吧,您只是发现它不起作用。你在想什么是有道理的:也许它应该失败。只是抽象类并非设计为作为元类工作,而是与“类型”协同工作。实际上,我觉得不可思议,因为大多数 Python 对象机制在与元类一起使用时碰巧“正常工作”——包括properties
特殊的 dunder 方法__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”(尽管这可能是个人喜好)
推荐阅读
- c# - API 请求对象的泛型或继承
- python - 在python中应用轮廓后如何从图像中提取文本?
- typescript - 受保护的类型,仍然不可分配
- java - 在android中以编程方式生成facebook开发哈希键
- polymer - *ngIf 等效于 lit-element/polymer
- kubernetes - Calico IP-in-IP 连接问题与 Kubernetes 上的嵌套容器
- c# - 在 .net core 3.1 中创建和执行工作流
- axapta - 函数 SalesTable2LineField.lineUpdateDescription 使用不正确
- python - 使用 Python 的 Web Scraping table 只是返回一个空列表
- swift - 将 1 个视图向后导航,然后向前导航到另一个视图(Whit 动画看起来像正常的推送)