Python 3.6.5 和 mypy 0.600
我写了代码:
from typing import List
class Animal():
pass
class Dog(Animal):
def __init__(self) -> None:
super()
def bark(self) -> None:
pass
class Cat(Animal):
def __init__(self) -> None:
super()
def meow(self) -> None:
pass
arr1: List[Dog] = [Dog(), Dog()]
arr2: List[Animal] = [Dog(), Dog()]
# error: Incompatible types in assignment (expression has type "List[Dog]", variable has type "List[Animal]")
arr3: List[Animal] = arr1
我不明白,为什么我有一个错误“赋值中的类型不兼容”和变量“arr3”。
Dog 是一个继承自 Animal 的类。
例如,变量“arr2”没有错误。
想象一下这是可能的:
arr3: List[Animal] = arr1
现在你认为你有动物列表,但这实际上是狗列表(请注意arr3
不是副本arr1
, 他们是the same list).
因为您认为这是动物列表,所以您可以添加Cat
to it.
但是,因为这实际上是狗的列表,所以您不能添加Cat
到它。否则你会失败AttributeError
在尝试使用狗特定的属性后。
更一般地说,列表是不变的 -List[Animal]
不能分配给List[Dog]
(因为它已经可以包含猫)并且List[Dog]
不能分配给List[Animal]
(因为你可以稍后添加猫)
这在Python中可能不明显,但你可以做简单的测试:
arr3: List[Animal] = arr1
arr3.append(Cat())
for dog in arr1:
print(dog.bark())
Mypy 不允许这样做,因为此分配可能会破坏您的代码逻辑
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)