注釈の確認
次のコードを実行したときの出力として、正しいものを1つ選べ。
def f(x: int, y: str = "a") -> bool:
return True
print(f.__annotations__)
- A
{'x': 'int', 'y': 'str', 'return': 'bool'} - B
{} - C
{'x': <class 'int'>, 'y': <class 'str'>, 'return': <class 'bool'>} - D
{'x': <class 'int'>, 'y': <class 'str'>}
正解と解説を見る
正解:C
関数の型注釈は __annotations__ に保存され、実行時には強制されない。ツール(mypy など)や実行時の検証ライブラリが利用する。
| 順 | 実行する行 | 実行後の変数 |
|---|---|---|
| 1 | `def f(x: int, y: str = "a") -> bool:` | — |
| 2 | `print(f.__annotations__)` | — |
| 結果 | 実際の出力 | {'x': <class 'int'>, 'y': <class 'str'>, 'return': <class 'bool'>} |
- A
誤り。文字列ではなく、型オブジェクトが入る。
- B
誤り。注釈は保存される。
- C
正しい。型注釈は
__annotations__に辞書として保存される。戻り値の注釈はreturnのキー。 - D
誤り。戻り値の注釈も含まれる。
このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。