跳转到主要内容
模块 9 · 第 1 课(共 4)课程中的33/36~12 min
模块课程(1/4)

类型提示:注释类型

类型提示(类型注释)是可选声明,表示 “此变量/参数的类型为 X”。 Python 不会在运行时验证它们: 它们适合您、您的编辑器(自动完成!)以及 mypy 或 pyright 执行静态类型检查。

注释变量

Python
nome: str = "Ada"
anni: int = 36
attivo: bool = True
prezzi: list[float] = [1.2, 3.4]

语法为 name: type = value。没有值,它是一个纯粹的声明:

Python
risultato: int  # nessuna assegnazione, solo "annuncio del tipo"

注释函数

Python
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+)

Python
nomi: list[str] = ["a", "b"]
mappa: dict[str, int] = {"x": 1}
coppia: tuple[int, str] = (1, "ok")
unici: set[int] = {1, 2, 3}

可选和联盟

可能是 None 的值:

Python
def trova_utente(id: int) -> str | None:
    if id == 1:
        return "Ada"
    return None

X | None 是现代语法(Python 3.10+)。等效:来自 typing 的 Optional[X]。 对于多种类型的联合:int | str | float。

打字:有用的工具

Python
from typing import Any, Callable

def applica(f: Callable[[int], int], x: int) -> int:
    return f(x)

valore: Any = "qualunque cosa"  # disabilita il check
  • Any =“不检查”(谨慎使用)。
  • Callable[[arg1, arg2], return] = 一个接受这些参数并返回该类型的函数。

mypy:类型检查器

您安装 mypy,运行 mypy file.py,它会告诉您类型是否对齐:

Bash
$ mypy script.py
script.py:5: error: Argument 1 to "somma" has incompatible type "str"; expected "int"

使用 mypy 检查类型

Python 的类型提示不是由解释器在运行时强制执行的;它们在执行过程中被忽略。要验证类型正确性,您必须通过在终端中执行命令 mypy script.py 来运行外部静态分析工具,例如 mypy。

自己尝试一下

锻炼#python.m9.l1.e1
尝试:0加载中...

定义一个函数 `double(numbers: list[int]) -> list[int]`,返回一个列表,其中每个元素乘以 2。使用 [1, 2, 3] 调用它并分配给 `r`。评估“r”。

正在加载编辑器...
显示提示

使用列表理解或 for 循环。

3 次尝试后可用的解决方案

复习练习

锻炼#python.m9.l1.e2
尝试:0加载中...

定义 `first_or_none(items: list[int]) -> int |如果列表非空,则返回 None`,否则返回 None。赋值 `a = first_or_none([10, 20])` 和 `b = first_or_none([])`。评估“(a, b)”。

正在加载编辑器...
显示提示

当列表不为空时,“if items”为真。

3 次尝试后可用的解决方案

额外的挑战

锻炼#python.m9.l1.e3
尝试:0加载中...

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 次尝试后可用的解决方案