【问题标题】:Python: typing a generic function that receives a type and returns an instance of that typePython:输入一个接收类型并返回该类型实例的泛型函数
【发布时间】:2021-08-13 13:09:07
【问题描述】:

我想在 Python 函数中添加类型,该函数将类型作为参数(实际上是特定类的子类型),并返回该类型的实例。考虑一个将特定类型作为参数的工厂,例如:

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

def make_animal(animal_type: Type[T]) -> T:  # <-- what should `Type[T]` be?
    return animal_type()

(显然这是一个非常简单的例子,但它演示了案例)

这感觉应该是可能的,但我找不到如何正确输入提示。

【问题讨论】:

    标签: python generics type-hinting


    【解决方案1】:

    这样的事情怎么样?

    from __future__ import annotations
    from typing import Type
    
    
    class Animal:
        ...
    
    
    def make_animal(animal_type: Type[Animal]) -> Animal:
        return animal_type()
    

    【讨论】:

      【解决方案2】:

      不确定您的问题是什么,您发布的代码是完全有效的 Python 代码。 typing.Type 正是你想要的:

      from typing import Type, TypeVar
      
      class Animal: ...
      class Snake(Animal): ...
      
      T = TypeVar('T', bound=Animal)
      
      def make_animal(animal_type: Type[T]) -> T:
          return animal_type()
      
      reveal_type(make_animal(Animal))  # Revealed type is 'main.Animal*'
      reveal_type(make_animal(Snake))   # Revealed type is 'main.Snake*'
      

      mypy-play 上查看 mypy 输出。

      【讨论】:

      • 我不知道为什么我错过了,谢谢
      猜你喜欢
      • 2016-10-16
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 2020-11-06
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多