【发布时间】:2021-12-12 16:09:02
【问题描述】:
假设我有一个Child 类,它是Parent 类的子类,以及一个接受Parent 子类实例列表的函数:
from typing import List
class Parent:
pass
class Child(Parent):
pass
def func(objects: List[Parent]) -> None:
print(objects)
children = [Child()]
func(children)
在此运行 mypy 会产生错误:
error: Argument 1 to "func" has incompatible type "List[Child]"; expected "List[Parent]"
如何为此创建类型?
附:有一种方法可以使用 Sequence 类型修复此特定错误:
def func(objects: Sequence[Parent]) -> None:
print(objects)
但这在其他类似情况下无济于事。我需要List,而不是Sequence。
【问题讨论】: