使用该类作为其方法中参数的类型提示 [英] Using the class as a type hint for arguments in its methods

查看:33
本文介绍了使用该类作为其方法中参数的类型提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面包含的代码会引发以下错误:

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 的检查器)将理解您的提示并正确注册.当通过 <访问 __annotations__ 时,Python 确实认识到这一点代码>typing.get_type_hints:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆