考虑到我通常使用,语言,我认为静态类型确实会让我在Python中的生活变得更轻松。我创建了这样一个类:
class node(object):
"""
properties, constructor, etc.
"""
def add_outneighbor(self, neighbor: node) -> None:
"""
do stuff
"""
Flake8告诉我node
在add_outneighbor
的定义中是一个未知类型。目前我正在解决isinstance(arg, type)
的问题,但这似乎违背了类型提示的目的。有没有更好的方法来做到这一点?This是我为了获得类型提示的信息而引用的资源。但我找不到任何关于自我参照的讨论。
2条答案
按热度按时间nzk0hqpo1#
解释器告诉您node是未知类型的原因是,除非您使用Python 4,否则在注解中使用它之前必须定义
node
。我建议插入以下声明:
from __future__ import annotations
,它会自动将注解存储为字符串。igsr9ssn2#
特殊的
Self
类型注解是在python3.11中引入的。文档中的使用示例:
使用原始问题的示例: