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

但如果我错了,请纠正我,并需要使用其他语法.
编辑:我注意到人们评论了类型提示不应该与 一起使用__eq__,并且授予,它不应该使用。但这不是我的问题的重点。我的问题是为什么该类不能用作方法参数中的类型提示,而可以在方法本身中使用?
事实证明,在使用 PyCharm 时,Python 类型提示对我非常有用。但是,当尝试在其方法中使用类自己的类型时,我遇到了一些奇怪的行为。
例如:
class Foo:
def __init__(self, id):
self.id = id
pass
def __eq__(self, other):
return self.id == other.id
Run Code Online (Sandbox Code Playgroud)
在这里,在键入 时other.,id不会自动提供该属性。我希望通过__eq__如下定义来解决它:
def __eq__(self, other: Foo):
return self.id == other.id
Run Code Online (Sandbox Code Playgroud)
然而,这给NameError: name 'Foo' is not defined. 但是当我在方法中使用该类型时,id会在写入后提供other.:
def __eq__(self, other):
other: Foo
return self.id == other.id
Run Code Online (Sandbox Code Playgroud)
我的问题是,为什么不能使用类自己的类型来提示参数的类型,而在方法中却是可能的?