如何为泛型工厂方法创建类型提示? [英] How to create type hinting for a generic factory method?

查看:52
本文介绍了如何为泛型工厂方法创建类型提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can type hints be declared to indicate that a function returns an instance of the class reference that is passed as an argument?

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

Declaring it as follows does not seem right, as it indicates that the returned type is the same as the type of the argument:

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

推荐答案

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

According to PEP-484, the right way to do this is to use Type[T] for the argument:

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

不过,我的编辑器似乎(还)不支持这一点.

It however seems like my editor does not (yet) support this.

这篇关于如何为泛型工厂方法创建类型提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆