LoginSignup
1
1

More than 1 year has passed since last update.

Pythonの関数アノテーションと型ヒント -> None の意味

Posted at

Vscodeではdef __init__でタブ補完すると、自動的に-> Noneと出てくるので調べてみた。

関数アノテーションと型ヒント

  • Pythonには、関数やクラスに対して アノテーション(型注釈) を付けることができる。
  • 引数や戻り値、クラスの属性やメソッドの戻り値などについて、そのデータ型を明示することができる機能。
  • 関数にアノテーションを付ける場合は、関数の定義の前に引数や戻り値に対するデータ型を
    ->を使って指定する。
  • 引数はそれぞれに対して、戻り値は関数定義の最後に指定する。また、関数アノテーションにはPythonの組み込み型や自作のクラスを指定することができる。
class Rectangle:
    width: int
    height: int

    def __init__(self, width: int, height: int) -> None:
        self.width = width
        self.height = height

    def area(self) -> int:
        return self.width * self.height
  • あくまでもただの注釈であり、実行時に型チェックが行われたりはしない。そのため、アノテーションで指定した型以外の引数を渡しても何も起こらない (エラーにならない)
def func_annotations_type(x: str, y: int)-> str:
    return x* y

print(func_annotations_type('abc', 3))
# abcabcabc

print(func_annotations_type(4, 3))
# 12
1
1
2

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
1
1