1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Type "Point" is not assignable to return type "Self@Point" when trying to annotate a...

Discussão em 'Python' iniciado por Stack, Outubro 8, 2024.

  1. Stack

    Stack Membro Participativo

    Consider this snippet of code:

    from typing import Self

    class Point:
    def __init__(self, x: int, y: int):
    self.x: int = x
    self.y: int = y
    def __add__(self, other: Self) -> Self
    return Point(self.x + other.x, self.y + other.y)


    I have this class, which represents a Point of coordinates x and y. Now I defined a method __add__(self, other) which, given two Points objects, returns another Point having as coordinates the sum of the two.

    I was type annotating this class and my first attempt was to make some something similar to this

    class Point:
    def __init__(self, x: int, y: int):
    self.x: int = x
    self.y: int = y
    def __add__(self, other: Point) -> Point
    return Point(self.x + other.x, self.y + other.y)


    However, this resulted in the following Pylance error: "Point is not defined". So, checking for possible solutions, I found that I could replace Point with Self from the typing module. But also, in this case, Pylance warns me that the Type "Point" is not assignable to return type "Self@Point". So I don't know how to type annotate my method correctly

    Continue reading...

Compartilhe esta Página