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

但如果我错了,请纠正我,并需要使用其他语法.
我试图找出类型的自引用如何与python3的类型注释一起工作 - 文档没有指定任何关于此的内容.
举个例子:
from typing import TypeVar, Optional, Generic
T = TypeVar('T')
class Node(Generic[T]):
left = None
right = None
value = None
def __init__(
self, value: Optional[T],
left: Optional[Node[T]]=None,
right: Optional[Node[T]]=None,
) -> None:
self.value = value
self.left = left
self.right = right
Run Code Online (Sandbox Code Playgroud)
此代码生成错误:
Traceback (most recent call last):
File "node.py", line 4, in <module>
class Node(Generic[T]):
File "node.py", line 12, in Node
right: Optional[Node[T]]=None,
NameError: name 'Node' is not defined
Run Code Online (Sandbox Code Playgroud)
这是使用Python 3.5.1
考虑两个模块(在同一文件夹中):
首先,person.py
from typing import List
from .pet import Pet
class Person:
def __init__(self, name: str):
self.name = name
self.pets = [] # type: List[Pet]
def adopt_a_pet(self, pet_name: str):
self.pets.append(Pet(pet_name))
Run Code Online (Sandbox Code Playgroud)
然后是pet.py
from .person import Person
class Pet:
def __init__(self, name: str, owner: Person):
self.name = name
self.owner = owner
Run Code Online (Sandbox Code Playgroud)
由于循环依赖,上述代码无法正常工作。您会得到一个错误:
ImportError: cannot import name 'Person'
Run Code Online (Sandbox Code Playgroud)
使其工作的一些方法:
例如:
class Pet:
def __init__(self, name: str, owner):
Run Code Online (Sandbox Code Playgroud)
到目前为止,我列出的所有选项中都有一些缺点。
还有另一种方法吗?一个让我能够
或者:是否有充分的理由改而采用我已经列出的解决方案之一?
python annotations circular-dependency type-hinting cross-reference
python ×3
python-3.5 ×2
python-3.x ×2
typing ×2
annotations ×1
pycharm ×1
type-hinting ×1
typechecking ×1