gpt4 book ai didi

python - 如何在 Python 中定义通用协变函数?

转载 作者:行者123 更新时间:2023-12-05 03:57:44 25 4
gpt4 key购买 nike

我想定义一个函数 example,它接受 Widget 类型的参数或任何扩展 Widget 的参数,并返回与争论。因此,如果 Button 扩展 Widget,则调用 example(Button()) 返回类型 Button

我尝试了以下方法:

T_co = TypeVar('T_co', Widget, covariant=True)

def example(widget: T_co) -> T_co:
...

但是类型检查器 (Pyright) 忽略了协方差。经过进一步研究,我在 PEP 484 中找到了一条注释:

Note: Covariance or contravariance is not a property of a type variable, but a property of a generic class defined using this variable. Variance is only applicable to generic types; generic functions do not have this property. The latter should be defined using only type variables without covariant or contravariant keyword arguments.

但是,如果我尝试定义一个没有注释中指定的协变参数的泛型函数:

T_co = TypeVar('T_co', Widget)

def example(widget: T_co) -> T_co:
...

我只能将 Widget 类型的值传递给函数(不是 Button)。

我怎样才能做到这一点?

最佳答案

我能够在 MyPy docs 中找到答案.原来我在寻找 bound,而不是 covariant。这可以像这样完成:

T = TypeVar('T', bound=Widget)

def example(widget: T) -> T:
...

关于python - 如何在 Python 中定义通用协变函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58379692/

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