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

类装饰器如何复用被传入函数的签名?原理解析

问题:跨类复用方法签名的装饰器原理疑惑

我实现了在服务类中统一管理设备实例创建的功能,不需要重复定义每个设备的__init__方法签名,还能给用户提供参数提示,功能完全正常,但我搞不懂背后的原理。

我的设备类示例如下:

class TestClass:
    # 后续说明该方法的用途
    @classmethod
    def create_instance(cls, x: int, y: int, z: int):
        return cls(x, y, z)

    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

我的需求是集中化管理这些设备的创建,但不想重复定义每个设备的__init__签名——用*args和**kwargs虽然能实现功能,但无法给用户提供参数提示,体验不好。

我通过以下步骤实现了需求:

  1. 定义TypeVar:
F = TypeVar('F', bound=Callable[..., Any])
  1. 定义类装饰器:
class copy_signature(Generic[F]):
    def __init__(self, _: F) -> None: pass
    def __call__(self, wrapped: Callable[..., Any]) -> F: return wrapped
  1. 在设备类中定义create_instance方法(如上面的TestClass代码所示)
  2. 在服务类中为创建方法添加注解:
class DeviceService:
    test_device: TestClass = None

    @copy_signature(TestClass.create_instance)
    @classmethod
    def create_test_device(cls, *args, **kwargs) -> TestClass:
        cls.test_device = TestClass.create_instance(*args, **kwargs)
        return cls.test_device

    @classmethod
    def get_test_device(cls) -> TestClass:
        return cls.test_device

现在功能完全符合预期,能正常给用户提供参数提示,但我有个疑问:装饰器的__init__方法只执行了pass,根本没用到传入的TestClass.create_instance引用,为什么必须传入这个参数?(我逻辑上知道要传才能拿到要复制签名的函数,但代码里明明没用到这个引用啊)

内容的提问来源于stack exchange,提问作者ningelsohn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 01:57:23