我在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函数注释来指定静态工厂方法的返回值的类型.我知道这是注释的理想用例之一.
class Trie:
@staticmethod
def from_mapping(mapping) -> Trie:
# docstrings and initialization ommitted
trie = Trie()
return trie
Run Code Online (Sandbox Code Playgroud)
PEP 3107指出:
函数注释只不过是一种在编译时将任意Python表达式与函数的各个部分相关联的方法.
Trie是Python中的有效表达式,不是吗?Python不同意或者更确切地说,找不到名称:
def from_mapping(mapping) -> Trie:
NameError: name 'Trie' is not defined
值得注意的是,如果指定了基本类型(例如objector int)或标准库类型(例如collections.deque),则不会发生此错误.
导致此错误的原因是什么?如何解决?
函数注释:PEP-3107
背景:我是 Linux 上使用 CPython 3.4x 的 PyCharm 用户。我发现注释函数参数和返回类型很有帮助。当我使用这些方法时,IDE 可以更好地提示。
问题:对于自链方法,如何注释方法返回值?如果我使用类名,Python 会在编译时抛出异常:NameError: name 'X' is not defined
示例代码:
class X:
def yaya(self, x: int):
# Do stuff here
pass
def chained_yaya(self, x: int) -> X:
# Do stuff here
return self
Run Code Online (Sandbox Code Playgroud)
作为一个技巧,如果我把X = None它放在类声明之前,它就可以工作。但是,我不知道这种技术是否有不可预见的负面影响。