[英]Python: typing a generic function that receives a type and returns an instance of that type
我想將類型添加到 Python function 中,它將類型作為參數(實際上是特定類的子類型),並返回該類型的實例。 考慮一個將特定類型作為參數的工廠,例如:
T = TypeVar('T', bound=Animal)
def make_animal(animal_type: Type[T]) -> T: # <-- what should `Type[T]` be?
return animal_type()
(顯然這是一個非常簡單的例子,但它演示了案例)
這感覺應該是可能的,但我找不到如何正確輸入提示。
不確定您的問題是什么,您發布的代碼是完全有效的 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 output 。
這樣的事情怎么樣?
from __future__ import annotations
from typing import Type
class Animal:
...
def make_animal(animal_type: Type[Animal]) -> Animal:
return animal_type()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.