代码之家  ›  专栏  ›  技术社区  ›  yotamN

获取子类的泛型参数

  •  0
  • yotamN  · 技术社区  · 2 年前

    我有一个泛型基类,我希望能够检查它提供的类型 typing.get_args 其工作原理如下:

    from typing import Generic, Tuple, TypeVarTuple, get_args
    
    T = TypeVarTuple("T")
    
    
    class Base(Generic[*T]):
        values: Tuple[*T]
    
    
    Example = Base[int, str]
    print(get_args(Example)) # (<class 'int'>, <class 'str'>)
    

    但当我继承类时,我会得到一个空的参数列表,如下所示:

    class Example2(Base[int, str]):
        pass
    
    
    print(get_args(Example2)) # ()
    

    我真正需要的是了解 values 所有物我可能有错误的方法,但我也尝试过使用 typing.get_type_hints 它似乎又回来了 Tuple[*T] 作为类型。

    那么我怎样才能得到类型化的参数呢?

    编辑:我需要知道 ,而不是对象。

    2 回复  |  直到 2 年前
        1
  •  3
  •   Paweł Rubin    2 年前

    使用 get_args 具有 __orig_bases__ :

    print(get_args(Example2.__orig_bases__[0]))  # prints "(<class 'int'>, <class 'str'>)"
    

    为了方便起见,可以将泛型类型参数存储在 __init_subclass__ 挂钩:

    from typing import Generic, TypeVarTuple, get_args
    
    T = TypeVarTuple("T")
    
    
    class Base(Generic[*T]):
        values: tuple[*T]
        type_T: tuple[type, ...]
    
        def __init_subclass__(cls) -> None:
            cls.type_T = get_args(cls.__orig_bases__[0])  # type: ignore
    
    
    class Example2(Base[int, str]):
        pass
    
    
    print(Example2.type_T)  # prints "(<class 'int'>, <class 'str'>)"
    
        2
  •  0
  •   frequent user    2 年前

    您也可以使用python函数

    help(package.class)
    

    以检索有关该类的文档。这不会直接返回所有可能的参数,但所有可能的变量都应该列在返回中。

    这将为您提供可用的参数,除非只需要检索参数来插入其他内容,在这种情况下,这可能不是您想要的。