【问题标题】:Python type hinting: class of given typePython 类型提示:给定类型的类
【发布时间】:2021-10-19 17:56:26
【问题描述】:

分享我发现的东西,以防对某人有帮助。

我想做的是创建一个通用方法,它接收一个类(类型)并返回该类型的一个实例。因为我强烈支持静态类型(双关语),所以我希望它是静态类型的。例如,如果您正在研究 IoC 服务提供商,这可能会很有用。

说在Java中,你可以有这样的签名:

public <T> getInstance(Class<T> clazz)

我想看看如何在 Python 中做到这一点。

【问题讨论】:

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


    【解决方案1】:
    from typing import TypeVar, Type
    
    T = TypeVar('T')
    def instantiate(self, t_type: Type[T]) -> T:
        return T()   # or whatever your code does
    
    # example
    class Foo:
       def some_method(self):
           pass
    
    f = instantiate(Foo)    # IDE recognizes f is Foo (even without you hinting it as `f: Foo`)
    f.some_method()         # IDE recognizes and suggests it when you're starting to type the method name.
    

    希望有人觉得它有用。

    【讨论】:

    • 您应该使用Callable[[], T] 而不是Type[T]。如果T 接受__init__ 中的参数,那么T() 只会抛出类型错误,前者不会后者。
    猜你喜欢
    • 2020-01-14
    • 2016-08-17
    • 2023-03-29
    • 2022-09-29
    • 1970-01-01
    • 2021-11-25
    • 2021-01-12
    • 2017-11-03
    • 2022-11-02
    相关资源
    最近更新 更多