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

如何检测__annotations__成员与泛型类参数类型是否一致?

解决泛型基类筛选匹配泛型参数的注解成员问题

要实现仅筛选出注解类型与泛型参数一致的成员,关键是正确获取子类继承泛型基类时传入的实际泛型参数,而非直接使用cls.__parameters__。具体实现如下:

修正后的基类代码

from typing import Generic, TypeVar, get_args, get_origin

T = TypeVar("T")

class MarkFinder(Generic[T]):
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        # 从子类的原始基类中提取目标泛型参数
        target_type = None
        for base in cls.__orig_bases__:
            if get_origin(base) is MarkFinder:
                target_type = get_args(base)[0]
                break
        
        cls.marked = tuple(
            name for name, annotated_type in cls.__annotations__.items()
            if annotated_type is target_type
        )

子类测试代码

T2 = TypeVar("T2")

class Inheritor(MarkFinder[T2]):
    a: T2
    b: int
    c: T2

# 验证结果
print(Inheritor.marked)  # 输出: ('a', 'c')

原方法无效的原因

直接用cls.__parameters__[0]对比的问题在于:

  • cls.__parameters__返回的是子类自身的泛型参数(若子类为泛型类),但我们需要的是基类被绑定的泛型参数(即MarkFinder[T2]中的T2)。
  • 通过cls.__orig_bases__可获取子类继承时的原始泛型基类定义,结合get_origin和get_args能精准提取出需要匹配的泛型参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 22:14:53