我在python 3中有以下代码:
class Position:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def __add__(self, other: Position) -> Position:
return Position(self.x + other.x, self.y + other.y)
Run Code Online (Sandbox Code Playgroud)
但是我的编辑器(PyCharm)说无法解析引用位置(在_add__方法中).我该如何指定我希望返回类型是类型__add__?
编辑:我认为这实际上是一个PyCharm问题.它实际上使用其警告中的信息和代码完成

但如果我错了,请纠正我,并需要使用其他语法.
在python 3中,我可以创建参数并返回类型注释.例:
class Graph:
def __init__(self, V: int, E: int, edges: list):
pass
@classmethod
def fromfile(cls, readobj: type(sys.stdin)):
pass
def V(self) -> int:
pass
def E(self) -> int:
pass
Run Code Online (Sandbox Code Playgroud)
问题是我无法使用当前类(Graph)的返回类型进行注释,该类尚未定义.例:
class Graph:
def reverse(self) -> Graph:
pass
Run Code Online (Sandbox Code Playgroud)
此代码有错误
def reverse(self) -> Graph:
NameError: name 'Graph' is not defined
Run Code Online (Sandbox Code Playgroud)
这些注释对于记录和允许IDE识别参数和返回类型=>启用自动完成非常有用
UPD:所以我提出的是要么是不可能的要么是需要一些我不喜欢的黑客攻击,所以我决定使用def reverse (self) -> 'Graph':
哪种文档是可以理解的,尽管违反了规则.缺点是它不适用于IDE自动完成.