繁体   English   中英

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__ function上使用它, 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM