![](/img/trans.png)
[英]mypy error: Incompatible return value type (got "object", expected "Dict[Any, Any]")
[英]mypy error: Incompatible return value type (got "Union[bool_, ndarray]", expected "bool")
我有一个 class,如下所示:
import numpy as np
class TestClass():
def __init__(self) -> None:
self.a = 1
def __eq__(self, other: object) -> bool:
if not isinstance(other, TestClass):
raise TypeError
return (np.all(other.a,self.a))
Mypy 返回错误Incompatible return value type (got "Union[bool_, ndarray]", expected "bool")
。 根据 np.all 的文档,此 function 应该返回具有这些类型输入的常规 boolean。 这种行为有原因吗?
这是 static 类型检查的限制(或至少,为numpy
给出的类型注释)。 当使用您显示的 arguments 调用时, np.all
function 返回一个bool
值,但是当使用其他keepdims=True
调用时,它可以返回其他类型(具体来说,如果它传递一个数组时,将返回一个相同的数组尺寸作为原始输入)。
您链接到的文档显示了这一点:
返回:全部:ndarray,bool
对于您显示的情况,您实际上根本不需要numpy
,因为您首先没有处理 arrays 。 为什么不使用and
运算符,或者内置的all
function?
def __eq__(self, other: object) -> bool:
if not isinstance(other, TestClass):
raise TypeError
return all((other.a, self.a)) # or bool(other.a and self.a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.