我试图了解类型提示在 Python 中是如何工作的——尤其是在儿童类中。我在处理一个项目时遇到了这个问题,并且能够在一个示例中重新创建该问题,如下所示。
环境:
- 蟒蛇:3.9.7
- 我的:0.910
- 操作系统:Ubuntu 20.04
示例代码:
from typing import List
import math
class Shape:
def area(self):
...
def perimeter(self):
...
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return math.pi * self.r * self.r
def perimeter(self):
return 2 * math.pi * self.r
class Cube(Shape):
def __init__(self, x):
self.x = x
self.corners = 4
def area(self):
return self.x * self.x
def perimeter(self):
return self.x * 4
class A:
def __init__(self, element: Shape):
self.element = element
class B(A):
def __init__(self, element: Cube):
super().__init__(element)
我不明白如何解决这个问题:
class AList:
def __init__(self, elements: List[Shape]):
self.elements = elements
class BList(AList):
def __init__(self, elements: List[Cube]):
super().__init__(elements) # This line is causing the Pyright error
print([x.corners for x in elements])
BList
我在课堂上收到以下 Pyright 错误super().__init__(elements)
:
[Pyright reportGeneralTypeIssues] [E] Argument of type "List[Cube]" cannot be assigned to parameter "elements" of type "List[Shape]" in function "__init__" TypeVar "_T@list" is invariant "Cube" is incompatible with "Shape"
我还在 mypy 中收到以下错误消息:
(pymmdt) eduardo@avocado-MS-7C83:~/Downloads$ mypy example.py
example.py:49: error: Argument 1 to "__init__" of "AList" has incompatible type "List[Cube]"; expected "List[Shape]"
example.py:49: note: "List" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
example.py:49: note: Consider using "Sequence" instead, which is covariant
Found 1 error in 1 file (checked 1 source file)
将继续努力,但任何建议/反馈将不胜感激。感谢您的时间!