我在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问题.它实际上使用其警告中的信息和代码完成

但如果我错了,请纠正我,并需要使用其他语法.
功能注释:PEP-3107
我跑过一段代码,展示了Python3的功能注释.这个概念很简单,但我想不出为什么这些在Python3中实现或者对它们有任何好用.也许SO可以启发我吗?
这个怎么运作:
def foo(a: 'x', b: 5 + 6, c: list) -> max(2, 9):
... function body ...
Run Code Online (Sandbox Code Playgroud)
参数后面后面的所有内容都是"注释",后面的信息->是函数返回值的注释.
foo.func_annotations将返回一个字典:
{'a': 'x',
'b': 11,
'c': list,
'return': 9}
Run Code Online (Sandbox Code Playgroud)
有这个有什么意义?
在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自动完成.
python ×3
python-3.x ×3
annotations ×2
class ×1
function ×1
pycharm ×1
python-3.5 ×1
typing ×1