[英]Python how to define type hint for union of all subclasses
假设我有一个在递归/树层次结构中有多个子类的类:
class Animal:
pass
class Cat(Animal):
pass
class HouseCat(Cat):
pass
我有一个函数,可以根据某些条件创建这些类的实例:
from typing import Union
def creator(condition) -> Union[Animal, Cat, HouseCat]:
# for codition1
return Animal()
# for codition2
return Cat()
# ...etc...
我的问题是 PyCharm 会显示类似这样的警告,如果我只使用-> Animal:
作为返回值注释:
my_list: List[Cat] = []
obj = creator(...)
my_list.append(obj) # <-- Expected type 'Cat' (matched generic type '_T'), got 'Animal' instead
有没有办法定义类型提示而不是为所有子类手动编写Union
?
您可以使用TypeVar
构造来编写带边界的代码:
from typing import TypeVar, List
class Animal:
pass
class Cat(Animal):
pass
class HouseCat(Cat):
pass
A = TypeVar('A', bound=Animal)
def creator() -> A:
pass
my_list: List[Cat] = []
obj = creator()
my_list.append(obj)
https://docs.python.org/3/library/typing.html#typing.TypeVar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.