gpt4 book ai didi

python - mypy 列表中对象继承的问题

转载 作者:太空狗 更新时间:2023-10-30 00:04:49 25 4
gpt4 key购买 nike

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 的副本,它们是 相同的列表)。

因为您认为这是动物列表,所以您可以向其中添加 Cat

但是,因为这实际上是狗的列表,所以您不能向其中添加 Cat。否则,在尝试使用特定于狗的属性后,您将在 AttributeError 上失败。

更一般地说,列表是不变的 - List[Animal] 不能分配给 List[Dog](因为它已经可以包含猫)和 List[ Dog]不能赋值给List[Animal](因为后面可以加cat)


这在 Python 中可能不明显,但你可以做简单的测试:

arr3: List[Animal] = arr1 
arr3.append(Cat())
for dog in arr1:
print(dog.bark())

Mypy 不允许这样做,因为这种分配可能会破坏您的代码逻辑

关于python - mypy 列表中对象继承的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50305636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com