How do I type hint a method with the type of the enclosing class?

前端 未结 5 598
抹茶落季
抹茶落季 2020-11-21 07:15

I have the following code in python 3:

class Position:

    def __init__(self, x: int, y: int):
        self.x = x
        self.y = y

    def __add__(self,          


        
5条回答
  •  温柔的废话
    2020-11-21 07:54

    The name 'Position' is not avalilable at the time the class body itself is parsed. I don't know how you are using the type declarations, but Python's PEP 484 - which is what most mode should use if using these typing hints say that you can simply put the name as a string at this point:

    def __add__(self, other: 'Position') -> 'Position':
        return Position(self.x + other.x, self.y + other.y)
    

    Check https://www.python.org/dev/peps/pep-0484/#forward-references - tools conforming to that will know to unwrap the class name from there and make use of it.(It is always important to have in mind that the Python language itself does nothing of these annotations - they are usually meant for static-code analysis, or one could have a library/framework for type checking in run-time - but you have to explicitly set that).

    update Also, as of Python 3.7, check pep-563 - as of Python 3.8 it is possible to write from __future__ import annotations to defer the evaluation of annotations - forward referencing classes should work straightforward.

提交回复
热议问题