gpt4 book ai didi

python - 如何在 Python 中获取子类的泛型类型

转载 作者:行者123 更新时间:2023-12-05 03:24:55 54 4
gpt4 key购买 nike

我有一个通用父类和一个以特定类型实现父类的子类:

T = TypeVar("T")

class Parent(ABC, Generic[T]):
def get_impl_t(self):
pass

class Child(Parent[int]):
pass

我想从父类获取子类的类型(参见 get_impl_t())。

我敢肯定,如果没有一些 hackery (inspect.getsource()?),这是不可能的,因为类型删除。如果它没有类层次结构,它将无法工作。

明显的解决方法是添加一个获取类型的抽象类方法或向父类的构造函数添加一个参数:

class Parent(ABC, Generic[T]):
def__init__(self, param_cls: Type[T]) -> None:
self.param_cls = param_cls

# or
@classmethod
@abstractmethod
def get_param_cls() -> Type[T]:
pass

这会增加一些维护开销,所以我想确保我没有遗漏任何东西。

最佳答案

你可以使用 typing.get_origin and typing.get_args .所以,效果是:

def get_impl_t(self):
for type_ in type(self).__orig_bases__:
if typing.get_origin(type_) is Parent:
return typing.get_args(type_)[0]

您想要如何处理事情将取决于您的用例的细节。但这里有一个演示:

In [1]: import typing

In [2]: from typing import TypeVar, Generic

In [3]: T = TypeVar("T")
...:
...: class Parent(Generic[T]):
...: def get_impl_t(self):
...: for type_ in type(self).__orig_bases__:
...: if typing.get_origin(type_) is Parent:
...: return typing.get_args(type_)[0]
...:
...: class Child(Parent[int]):
...: pass
...:

In [4]: Child().get_impl_t()
Out[4]: int

还有另一个 child :

In [5]: class AnotherChild(Parent[str]):
...: pass
...:

In [6]: AnotherChild().get_impl_t()
Out[6]: str

关于python - 如何在 Python 中获取子类的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72149212/

54 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com