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

如何为数据类添加注解,使__call__返回匹配初始化类型的实例?

解决方案

你需要用绑定基类的TypeVar配合泛型类来实现类型关联,让类型检查器能追踪初始化时传入的具体类型,确保__call__返回对应实例。具体修改如下:

from dataclasses import dataclass
from typing import TypeVar, Type, Generic

class BaseType: ...
class PathType(BaseType): ...
class DataType(BaseType): ...

# 定义绑定到BaseType的TypeVar,限制只能是BaseType的子类
T = TypeVar('T', bound=BaseType)

@dataclass
class InterfaceInfo(Generic[T]):
    # what的类型是T的类对象
    what: Type[T]
    name: str

    # __call__返回T类型的实例
    def __call__(self, *args, **kwargs) -> T:
        return self.what(*args, **kwargs)

# 类型检查器会识别:这里的instance1调用后返回PathType实例
instance1 = InterfaceInfo(PathType, "path")
result1 = instance1()  # 类型推断为PathType

# 这里的instance2调用后返回DataType实例
instance2 = InterfaceInfo(DataType, "path")
result2 = instance2()  # 类型推断为DataType

关键说明

  • TypeVar('T', bound=BaseType)限定了T只能是BaseType或其子类,确保传入的what是合法类型。
  • 让InterfaceInfo继承Generic[T],把类变成泛型类,这样每个实例的类型参数T会和初始化时传入的Type[T]绑定。
  • 此时类型检查器能准确推断:用PathType初始化的InterfaceInfo实例,调用后必然返回PathType对象,不会再混淆成DataType。

内容的提问来源于stack exchange,提问作者Steven Van Ingelgem

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 05:10:02