使用类作为其方法中参数的类型提示[重复]

发布于 2021-01-29 15:17:12

这个问题已经在这里有了答案

如何键入带有封闭类类型的方法? (6个答案)

8个月前关闭。

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

NameError: name 'Vector2' is not defined

在这一行:

def Translate (self, pos: Vector2):

为什么Python无法Vector2Translate方法中识别我的类?

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
关注者
0
被浏览
52
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    因为当它遇到时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的答案



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看