【问题标题】:Python type hinting with constraint on type superclass对类型超类有约束的 Python 类型提示
【发布时间】:2016-03-27 02:09:06
【问题描述】:

是否可以在 Python 中添加类型提示并限制类型的超类?例如,我想要这样的东西:

def foo(g: T(S)) -> T:
    pass

这将是一个函数,它接受T 类型的参数gT 必须是类SS 本身的子类,并且函数的返回值是@ 类型987654329@.

C# 中的等效函数类似于

public static void foo<T>(T g) where T : S
{
}

我查看了PEP484,但似乎没有任何相关内容。

【问题讨论】:

标签: python


【解决方案1】:

根据PEP484,您想要的语法似乎是:

from typing import TypeVar

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

def foo(g: T) -> T:
    pass

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 2011-01-17
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 2017-01-21
    相关资源
    最近更新 更多