python/응용

type hints Self type

wefree 2023. 10. 17. 16:47

https://stackoverflow.com/a/33533514

 

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

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, other: Position) -> Position:

stackoverflow.com

 

from __future__ import annotations

from dataclasses import dataclass


@dataclass
class Vector:
    x: float
    y: float

    def __add__(self, other: Vector):
        return Vector(self.x + other.x, self.y + other.y)

 

  • from __future_ import annotations 가 없으면 def __add__(self, other: Vector) 에서 Vector class 를 인식할 수 없다고 에러가 발생한다.
  • from __future__ import annotations - this must be imported before all other imports. 

 

python 3.11 부터는 아래처럼 가능

https://medium.com/techtofreedom/8-levels-of-using-type-hints-in-python-a6717e28f8fd

from typing import Self

class ListNode:
    def __init__(self, prev_node: Self) -> None:
        pass