You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python类方法的装饰器添加正确的类型注解?

问题:为类方法编写可访问self的装饰器的类型注解

我有一个包含多个相似方法的类:

class Actions:
    def action1(self, parameter1: int) -> None:
        ...

    def action2(self, parameter2: int) -> None:
        ...

我想要为这些方法创建一个可访问self的装饰器,基本结构如下:

def action(method: Callable[???]) -> Callable[???]:
    def wrapper(self, *args, **kwargs) -> None:
        method(self, *args, **kwargs)
        ...
    return wrapper

请问该装饰器的类型注解应该如何编写?

我目前尝试了如下写法(其中Actions是仅包含必要属性的协议类):

from typing_extensions import Concatenate, ParamSpec
from typing import Callable


P = ParamSpec("P")


def action(
    method: Callable[Concatenate[Actions, P], None]
) -> Callable[Concatenate[Actions, P], None]:
    def wrapper(self: Actions, *_args: P.args, **kwargs: P.kwargs) -> None:
        method(self, *args, **kwargs)
        ...

这段代码在Mypy中可以正常识别,但PyCharm会对类似actions.action1(parameter1=0)的调用报错:Expected type 'Actions', got 'int' instead。


内容的提问来源于stack exchange,提问作者Данила Мамутов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 20:22:03