首页 > 解决方案 > 类实例的类型

问题描述

我有以下代码,在 Python 3.9.2 上运行,我无法工作。

from__future__ import annotations

class P():
    def __eq__(self:P, comparand:P) -> bool:
        return false

Mypy抱怨说

Argument 1 of "__eq__" is incompatible with supertype "object";
supertype defines the argument types as "object"

关于如何做到这一点的任何建议?

标签: pythontypesmypy

解决方案


问题是eq方法适用于任何对象,没有 :P 它会起作用。您可以在代码中使用 isisinstance 检查参数的类型(如有必要)。

from__future__ import annotations

class P():
    def __eq__(self, comparand) -> bool:
        return false

推荐阅读