【发布时间】:2023-04-06 23:57:01
【问题描述】:
我有以下代码来比较基类的当前(空)实现所需函数及其子类,这些子类必须以某种不同的方式实现它们,以便在运行时被认为是可接受的。如果不使用 metaclass=ABCMeta 并在这些基类方法上实现 @abstractmethod 装饰器,我该怎么做呢?现在,我在项目的多个地方写了以下 __init_subclass__ 钩子在我的临时、无元类的抽象基类上,但感觉不对。
import inspect
class AbstractThing:
def __init__(self, topic: str, thing: Thing):
thing.subscriptions[topic] = self.on_message
thing.on_connected.append(self.on_connected)
thing.on_disconnected.append(self.on_disconnected)
def __init_subclass__(cls):
required_methods = ['on_connected', 'on_disconnected', 'on_message']
for f in required_methods:
func_source = inspect.getsourcelines(getattr(cls, f))
# if this class no longer inherits from `Object`, the method resolution order will have updated
parent_func_source = inspect.getsourcelines(getattr(cls.__mro__[-2], f))
if func_source == parent_func_source:
raise NotImplementedError(f"You need to override method '{f}' in your class {cls.__name__}")
def on_connected(self, config: dict):
pass
def on_disconnected(self):
pass
def on_message(self, msg: str):
pass
有没有更好的方法来做到这一点?如果我在定义此 AbstractThing 的子类时在编辑器中遇到类型检查错误,则可以加分。
【问题讨论】:
标签: python abstract-class inspect