モジュールのレッスン (1/4)
型ヒント: 型の注釈付け
型ヒント (型注釈) は、次のような オプションの宣言 です。 「この変数/パラメータの型は X です。」 Python は実行時にそれらを検証しません。 これらはあなた、あなたのエディタ (オートコンプリート!)、および mypy や pyright 静的型チェックを実行します。
変数に注釈を付ける
nome: str = "Ada"
anni: int = 36
attivo: bool = True
prezzi: list[float] = [1.2, 3.4]構文は name: type = value です。値がなければ、それは純粋な宣言です。
risultato: int # nessuna assegnazione, solo "annuncio del tipo"関数に注釈を付ける
def saluta(nome: str, urlante: bool = False) -> str:
s = f"Ciao {nome}"
return s.upper() if urlante else s
def somma(numeri: list[int]) -> int:
return sum(numeri)構文: 各パラメータの場合は param: type、戻り値の場合は -> type です。
何も返さない関数は -> None を使用します。
組み込みのジェネリック型 (Python 3.9 以降)
nomi: list[str] = ["a", "b"]
mappa: dict[str, int] = {"x": 1}
coppia: tuple[int, str] = (1, "ok")
unici: set[int] = {1, 2, 3}オプションとユニオン
None の可能性がある値:
def trova_utente(id: int) -> str | None:
if id == 1:
return "Ada"
return NoneX | None は最新の構文 (Python 3.10 以降) です。同等: typing から Optional[X]。
複数のタイプの共用体の場合: int | str | float。
タイピング: 便利なツール
from typing import Any, Callable
def applica(f: Callable[[int], int], x: int) -> int:
return f(x)
valore: Any = "qualunque cosa" # disabilita il checkAny= 「チェックしない」(慎重に使用してください)。Callable[[arg1, arg2], return]= これらのパラメータを受け取り、その型を返す関数。
mypy: 型チェッカー
mypy をインストールし、mypy file.py を実行すると、タイプが揃っているかどうかがわかります。
$ mypy script.py
script.py:5: error: Argument 1 to "somma" has incompatible type "str"; expected "int"mypyで型を確認する
Python の型ヒントは、実行時にインタープリターによって適用されません。実行中は無視されます。型の正確性を検証するには、ターミナルでコマンド mypy script.py を実行して、mypy などの外部静的解析ツールを実行する必要があります。
自分で試してみてください
各要素を 2 倍したリストを返す関数 `double(numbers: list[int]) -> list[int]` を定義します。これを [1, 2, 3] で呼び出して `r` に代入します。 「r」を評価します。
ヒントを表示
リスト内包表記または for ループを使用します。
3 回の試行後に解決策が利用可能になります
復習演習
`first_or_none(items: list[int]) -> int | を定義します。 None` は、リストが空でない場合は最初の要素を返し、それ以外の場合は None を返します。 `a = first_or_none([10, 20])` および `b = first_or_none([])` を代入します。 `(a, b)`を評価します。
ヒントを表示
リストが空でない場合、`if items` は true になります。
3 回の試行後に解決策が利用可能になります
追加の課題
Write a function `double_value(n: int) -> int` that takes an integer, multiplies it by 2, and returns the result. Make sure to specify type hints for both the parameter and the return value. Finally, evaluate `double_value(5)`.
ヒントを表示
n: int をパラメータとして使用し、関数シグネチャの後に -> int を使用します。
3 回の試行後に解決策が利用可能になります