专用 Python 通用类中的类型

问题描述 投票:0回答:1

考虑以下通用类,然后对其进行专门化。

from typing import Generic, TypeVar

T = TypeVar("T")
T1 = TypeVar("T1")
T2 = TypeVar("T2")

class X(Generic[T1, T2]):
    x: T1
    y: T2

class Y(Generic[T], X[float, T]):
    pass

class Z(Y[int]):
    pass

有没有办法获得

Z
的专业化值,在这种情况下为
(float, int)

python generics typing
1个回答
0
投票

可以获取类型参数作为类的

__args__
,递归遍历继承树获取所有参数:

def all_class_args(cls):
    args = []
    if hasattr(cls, '__origin__'):
        args.extend(all_class_args(cls.__origin__))
    if hasattr(cls, '__args__'):
        args.extend(cls.__args__)
    if hasattr(cls, '__orig_bases__'):
        args.extend(
            a
            for base in cls.__orig_bases__
            for a in all_class_args(base)
            if isinstance(a, type)
        )
    return args

print(all_class_args(Z))  # [<class 'float'>, <class 'int'>]
© www.soinside.com 2019 - 2024. All rights reserved.