抽象类中为回调属性赋值NotImplementedError的非exec优雅实现问询
解决方案
你可以用以下几种更优雅的方式替代lambda: exec("raise NotImplementedError()"):
1. 定义类内专用方法(最推荐)
直接在抽象类里写一个专门的方法抛出NotImplementedError,再把这个方法赋值给回调属性。这种写法可读性强,类型检查工具也能正常识别,完全规避exec的hack写法:
from typing import Callable class YourAbstractClass: def __init__(self): # 注意:无参数回调的正确类型标注是 Callable[[], None],而非 Callable[[None], None] self._button_clicked: Callable[[], None] = self._raise_not_implemented def _raise_not_implemented(self) -> None: raise NotImplementedError("子类必须实现_button_clicked回调逻辑")
2. 使用嵌套函数
如果不想在类中新增独立方法,也可以在__init__里定义嵌套函数:
from typing import Callable class YourAbstractClass: def __init__(self): def _raise_error(): raise NotImplementedError("未实现按钮点击回调") self._button_clicked: Callable[[], None] = _raise_error
为什么原来的写法行不通?
- 赋值语句右侧必须是表达式,而
raise NotImplementedError()是语句,直接赋值会触发SyntaxError。 - lambda表达式的主体只能是单个表达式,无法包含
raise这类语句,所以不能直接在lambda里写raise。
用exec的lambda写法虽然能运行,但可读性差,IDE无法做语法检查,还可能隐藏潜在问题,完全不推荐。
内容的提问来源于stack exchange,提问作者vince6e74
相关产品推荐
相关产品推荐

