Python 键入内部 class 方法
Python typing internal class methods
我正在尝试在我的代码中使用更多的输入来提高它的可读性和安全性。目前,我正在尝试通过平等覆盖方法来做到这一点:
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不允许这种类型引用吗?如果是这样,我该如何解决?
可以这样注释:
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>
我正在尝试在我的代码中使用更多的输入来提高它的可读性和安全性。目前,我正在尝试通过平等覆盖方法来做到这一点:
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不允许这种类型引用吗?如果是这样,我该如何解决?
可以这样注释:
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>