使用类作为其方法中参数的类型提示 [英] Using the class as a type hint for arguments in its methods
问题描述
我下面包含的代码引发以下错误:
The code I have included below throws the following error:
NameError: name 'Vector2' is not defined
在此行:
def Translate (self, pos: Vector2):
为什么Python无法在Translate
方法中识别我的Vector2
类?
Why does Python not recognize my Vector2
class in the Translate
method?
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自然会抱怨.
Because when it encounters Translate
(while compiling the class body), Vector2
hasn't been defined yet (it is currently compiling, name binding hasn't been performed); Python naturally complains.
由于这是一种常见的情况(在该类的主体中键入类的提示),因此应使用
Since this is such a common scenario (type-hinting a class in the body of that class), you should use a forward reference to it by enclosing it in quotes:
class Vector2:
# __init__ as defined
def Translate(self, pos: 'Vector2'):
self.x += pos.x
self.y += pos.y
Python(以及所有符合PEP 484
的检查器)将理解您的提示并进行适当的注册.通过 typing.get_type_hints
访问__annotations__
时,Python会识别出此错误>:
Python (and any checkers complying to PEP 484
) will understand your hint and register it appropriately. Python does recognize this when __annotations__
are accessed through typing.get_type_hints
:
from typing import get_type_hints
get_type_hints(Vector2(1,2).Translate)
{'pos': __main__.Vector2}
此功能自Python 3.7起已更改;请参阅下面的 abarnert的答案.
这篇关于使用类作为其方法中参数的类型提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!