python-3.x - Python 类型提示 : self-referential type checking

标签 python-3.x type-hinting

考虑到我通常使用 C 语言工作,我认为静态类型确实会让我在 Python 中的生活更轻松。我创建了一个这样的类:

class node(object):
    """
    properties, constructor, etc.
    """

    def add_outneighbor(self, neighbor: node) -> None:
        """
        do stuff
        """

Flake8 告诉我 nodeadd_outneighbor 定义中的未知类型。目前我正在解决 isinstance(arg, type) 的问题,但这似乎违背了拥有类型提示的目的。有一个更好的方法吗? This是我为了获取有关类型提示的信息而引用的资源,但我找不到有关此自引用问题的任何讨论。

最佳答案

解释器告诉你 node 是未知类型的原因是,除非你使用 Python 4,否则必须先定义 node 才能在注解中使用它。

我建议插入以下语句:from __future__ import annotations,它将自动将注释存储为字符串。那你就不会再有这个问题了

关于python-3.x - Python 类型提示 : self-referential type checking,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53695453/

相关文章:

python - 为什么 List 不能包含多种类型?

python - 在类构造函数中表达兄弟嵌套类的类型提示

python - 使用lxml解析kml文件

python - 如何对列表进行排序首先写入相同的元素,然后按升序排列

python-3.x - 我应该使用 == 进行字符串比较吗?

python - 如何修改 pandas df 以调整系列情节的起点?

python - 通用代码的类型提示

python - 如何通过处理连续换行符等情况来读取csv文件?

python - type() 函数没有为 boto3 sqs 对象返回正确的结果?

python - mypy如何使用typing.TYPE_CHECKING解决循环导入注解问题?