【问题标题】:How to create type hinting for a generic factory method?如何为通用工厂方法创建类型提示?
【发布时间】:2017-02-14 13:03:06
【问题描述】:

如何声明类型提示以指示函数返回作为参数传递的类引用的实例?

如下声明似乎不对,因为它表明返回的类型与参数的类型相同:

from typing import TypeVar


T = TypeVar('T')

def my_factory(some_class: T) -> T:
    instance_of_some_class = some_class()
    return instance_of_some_class

示例用法:

class MyClass:
    pass

my_class = my_factory(MyClass)  # Inferred type should be MyClass

【问题讨论】:

标签: python python-3.x type-hinting


【解决方案1】:

根据PEP-484,正确的做法是使用Type[T]作为参数:

from typing import TypeVar, Type


T = TypeVar('T')

def my_factory(some_class: Type[T]) -> T:
    instance_of_some_class = some_class()
    return instance_of_some_class

然而,我的编辑器似乎(还)不支持这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 2014-09-24
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多