Python键入内部类方法

时间:2019-09-30 00:24:29

标签: python python-3.x python-typing

我正在尝试在代码中使用更多类型的输入,以提高其可读性和安全性。目前,我正在尝试使用相等性替代方法执行此操作:

class X:
    def __init__(self, t):
        self._t = t

    def __eq__(self, other: X):
        return self._t == other._t

这似乎很简单,但是我得到一个错误:

NameError: name 'X' is not defined

python不允许这种类型的类型引用吗?如果是这样,我该如何解决?

1 个答案:

答案 0 :(得分:0)

可以像这样注释它

class X:
    def __init__(self, t):
        self._t = t

    def func(self, other: "X"):
        return self._t == other._t

但是正如user2357112所说,如果您在__eq__函数上使用它,mypy会告诉您:

a.py:5: error: Argument 1 of "__eq__" incompatible with supertype "object"
a.py:5: note: It is recommended for "__eq__" to work with arbitrary objects, for example:
a.py:5: note:     def __eq__(self, other: object) -> bool:
a.py:5: note:         if not isinstance(other, X):
a.py:5: note:             return NotImplemented
a.py:5: note:         return <logic to compare two X instances>