因为当它遇到时
Translate(在编译类主体时),
Vector2尚未被定义(它正在编译中,尚未执行名称绑定);Python自然会抱怨。
由于这是一种常见的情况(在该类的主体中键入一个类的类型),因此应使用对它的
前向引用
,将其括在引号中:
class Vector2: # __init__ as defined def Translate(self, pos: 'Vector2'): self.x += pos.x self.y += pos.y
Python(以及所有符合的检查程序
PEP484)将理解您的提示并进行适当的注册。
__annotations__通过
typing.get_type_hints以下方式访问时,Python确实会识别出这一点:
from typing import get_type_hintsget_type_hints(Vector2(1,2).Translate){'pos': __main__.Vector2}从Python
3.7起已更改。请参阅下面的abarnert的答案。


![使用类作为其方法中参数的类型提示[重复] 使用类作为其方法中参数的类型提示[重复]](http://www.mshxw.com/aiimages/31/668298.png)
