使用类作为其方法中参数的类型提示[重复]
这个问题已经在这里有了答案 :
如何键入带有封闭类类型的方法? (6个答案)
8个月前关闭。
我下面包含的代码引发以下错误:
NameError: name 'Vector2' is not defined
在这一行:
def Translate (self, pos: Vector2):
为什么Python无法Vector2
在Translate
方法中识别我的类?
class Vector2:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def Translate(self, pos: Vector2):
self.x += pos.x
self.y += pos.y
-
因为当它遇到时
Translate
(在编译类主体时),Vector2
尚未被定义(它正在编译中,尚未执行名称绑定);Python自然会抱怨。由于这是一种常见的情况(在该类的主体中键入一个类的类型),因此应使用对它的
前向引用
,将其括在引号中:class Vector2: # __init__ as defined def Translate(self, pos: 'Vector2'): self.x += pos.x self.y += pos.y
Python(以及所有符合的检查程序
PEP 484
)将理解您的提示并进行适当的注册。__annotations__
通过typing.get_type_hints
以下方式访问时,Python确实会识别出这一点:from typing import get_type_hints get_type_hints(Vector2(1,2).Translate) {'pos': __main__.Vector2}
从Python
3.7起已更改。请参阅下面的abarnert的答案。