Using a class as a hint type for arguments in its methods

The code below shows the following error:

NameError: name 'Vector2' is not defined 

in this line:

def Translate (self, pos: Vector2):

Why doesn't Python recognize my class Vector2in a method 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
+16
source share
2 answers

Because when it encounters Translate(when compiling the body of the class), it Vector2has not yet been defined (currently it compiles, the name binding has not been done); Python naturally complains.

Since this is such a common scenario (hints of the class type in the body of this class), you should use a direct link to it, enclosing it in quotation marks:

class Vector2:    
    # __init__ as defined

    def Translate(self, pos: 'Vector2'):    
        self.x += pos.x
        self.y += pos.y

Python ( , PEP 484) . Python , __annotations__ typing.get_type_hints:

from typing import get_type_hints

get_type_hints(Vector2(1,2).Translate)
{'pos': __main__.Vector2}

Python 3.7; . abarnert .

+22

, , () , Python 3.7 ( PEP 563). 1 :

from __future__ import annotations
class C:
    def spam(self, other: C) -> C:
        pass

__future__. 4.0.

, Python 3.6 , , .

Mypy , Python 3.6 - , , , NameError, .


1. PEP 484, , , . PEP 563/Python 3.7 - "".

+7

Source: https://habr.com/ru/post/1657803/


All Articles