45
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonでクラスの引数や戻り値の型アノテーションに自己のクラスを指定する

Last updated at Posted at 2021-01-01

型アノテーションに自己のクラスを指定できない

list_node.py
class ListNode:
    def __init__(self, val: int, next: ListNode):
        self.val = val
        self.next = next

例えば、上記(片方向連結リストのコンストラクタ)のように型アノテーションを書くと、ListNodeが定義されていないと警告が表示される。

undefined name 'ListNode'

Python3.7以上の場合: from __future__ import annotationsを使用する

list_node.py
from __future__ import annotations


class ListNode:
    def __init__(self, val: int, next: ListNode):
        self.val = val
        self.next = next

assert ListNode.add.__annotations__ == {
    'next': 'ListNode'
}

Python3.7未満の場合: 文字列を使用する

Python3.7未満ではfrom __future__ import annotationsを使用できないため、文字列を使用する。

list_node.py
class ListNode:
    def __init__(self, val: int, next: 'ListNode'):
        self.val = val
        self.next = next

参考

45
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
45
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?