![](/img/trans.png)
[英]mypy error: Incompatible return value type (got "object", expected "Dict[Any, Any]")
[英]error: Incompatible return value type (got "Tuple[Tuple[float, float], ...]", expected "List[Any]")
在尝试实现静态类型时,我在指定以下函数的返回类型时遇到了一些困难:
def create_hexagon_coordinates(origin: tuple, unit: float, plot=False) -> list[Tuple[float,float]]:
unit = 3**0.5
mid_left = (float(-unit), 0.)
top_left = (float(-unit / 2), float(unit**2 / 2))
hexagon = (
mid_left,
top_left,
)
return hexagon
错误信息是:
错误:返回值类型不兼容(得到“Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float], Tuple[float, float], Tuple[float, float], Tuple[float,浮动]]”,预期“列表[任何]”)
我认为通过在列表中包含元素类型的规范,比List[Any]
更明确会更好。 但是,如果我包含它,它还需要我指定列表的长度(因为它希望我指定所有元素的完整类型)。 由于列表中的所有元素类型都在错误消息中返回。
即使我将List[Tuple[float,float]]
包含在此处所示的大写字母中,错误也会变为:
错误:“列表”不需要类型参数,但给出了 1
错误:返回值类型不兼容(得到“Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float], Tuple[float, float], Tuple[float, float], Tuple[float,浮动]]”,预期为“_ast.List”)
因此,我想问一下,是否建议指定列表中元素的类型(如果它是已知的并且每个元素都相同),列表(不确定的)长度,如果是,如何做到这一点?
我犯了多个小错误,导致了错误消息。 一个可行的解决方案是:
def create_hexagon_coordinates(
origin: tuple, unit: float, plot=False
) -> list[tuple[float, float]]:
"""Creates a list of coordinates of a hexagon, with a horizontal line in
the top and bottom. Top right coordinate is named A, mid right coordinate
is named B, and clockwise onwards.
:param origin: tuple: Optional parameter to set the origin of the hexagon.
:param unit: float: Optional parameter to set the length of the standard
unit.
"""
if origin is None:
origin = (0, 0)
top_right: tuple[float, float] = (float(unit / 2), float(unit**2 / 2))
mid_right: tuple[float, float] = (float(unit), 0.0)
bottom_right: tuple[float, float] = (
float(unit / 2),
float(-(unit**2) / 2),
)
bottom_left: tuple[float, float] = (
float(-unit / 2),
float(-(unit**2) / 2),
)
mid_left: tuple[float, float] = (float(-unit), 0.0)
top_left: tuple[float, float] = (float(-unit / 2), float(unit**2 / 2))
hexagon: list[tuple[float, float]] = [
top_right,
mid_right,
bottom_right,
bottom_left,
mid_left,
top_left,
]
if plot:
figure(figsize=(8, 8), dpi=80)
plt.xlim(-5, 5)
plt.ylim(-5, 5)
for point in hexagon:
plt.scatter(point[0], point[1])
plt.show()
return hexagon
tuple
而不是列表创建的。 所以无论我在方括号内放什么, list[tuple..]
都不起作用。-> List[..]
和实际返回的对象之间的差异。tuple
元素float
,这意味着中间有一些int
类型。 我没有注意到这一点。 但是,我认为这就是错误提示类型any
的原因。 总而言之,如果列表中的所有元素都属于同一类型,则可以编写list[sometype]
其中sometype
是列表中每个元素的类型。 我必须确保这些类型确实是相同的。
我还有两件事不清楚,它们是:
list[float,int]
。但是,这些是单独的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.