在 Python 中注释函数

在 Python 中注释函数
最新回答
る午夜上浓妆

2020-11-11 11:03:38

在Python中,函数注释主要通过类型提示(Type Hints)实现,用于明确参数和返回值的类型,提升代码可读性和可维护性。以下是具体注释方法和示例:

1. 基础函数注释

使用参数名: 类型和-> 返回值类型的语法标注类型:

def greet(name: str) -> str: return f"Hello, {name}"
  • 参数:name应为str类型。
  • 返回值:函数返回培猛str类型。
2. 回调函数与Callable

当函数作为参数或返回值时晌滑,使用Callable标注其参数和返回类型:

from typing import Callabledef apply_operation(x: int, operation: Callable[[int], int]) -> int: return operation(x)def square(n: int) -> int: return n * nresult = apply_operation(5, square) # 返回25
  • operation:接受一个int参数,返回int。
  • apply_operation:调用传入的函数并返回结果。
3. 泛型函数与TypeVar

通过TypeVar定义泛型类型,适用于多种类型的函数:

from typing import TypeVar, SequenceT = TypeVar("T") # 定义泛型类型Tdef first_element(sequence: Sequence[T]) -> T: return sequence[0]print(first_element([1, 2, 3])) # 返回1(int)print(first_element(["a", "b"])) # 返回"a"(str)
  • Sequence[T]:表示接受任何序列类型(如列表、元组)。
  • 返回值:与序列元素类型一致。
4. 联合类型与Union

当参数可能为多种类型时,宴中腊使用Union标注:

from typing import Uniondef process_value(value: Union[int, float]) -> float: return float(value)print(process_value(5)) # 返回5.0print(process_value(3.14)) # 返回3.14
  • value:可以是int或float类型。
5. 类型别名

为复杂类型定义别名,简化代码:

from typing import Callable, TypeVarT = TypeVar("T")Number = Union[int, float]def multiplier(factor: Number) -> Callable[[Number], Number]: def inner(value: Number) -> Number: return value * factor return innerdouble = multiplier(2)print(double(5)) # 返回10.0
  • Number:表示int或float的联合类型。
  • multiplier:返回一个接受Number并返回Number的函数。
6. 高阶函数注释

结合Callable和Iterable标注高阶函数(如map、filter):

from typing import Iterable, Callable, TypeVarT = TypeVar("T")U = TypeVar("U")def mymap(array: Iterable[T], fn: Callable[[T], U]) -> Iterable[U]: return map(fn, array)def square(n: int) -> int: return n * nprint(list(mymap([1, 2, 3], square))) # 返回[1, 4, 9]
  • array:可迭代对象,元素类型为T。
  • fn:接受T类型参数,返回U类型。
  • 返回值:可迭代对象,元素类型为U。
7. 泛型类注释

通过继承Generic定义泛型类:

from typing import Generic, TypeVar, ListT = TypeVar("T")class Stack(Generic[T]): def __init__(self): self.items: List[T] = [] def push(self, item: T) -> None: self.items.append(item) def pop(self) -> T: return self.items.pop()stack = Stack[int]()stack.push(10)print(stack.pop()) # 返回10
  • Stack[T]:类中的items列表和操作均基于泛型T。
8. 静态类型检查

使用mypy等工具验证注释的正确性:

  1. 安装mypy:pip install mypy
  2. 运行检查:mypy script.py
为什么使用函数注释?
  • 提升可读性:明确参数和返回值的类型,便于团队协作。
  • 静态检查:通过mypy提前发现类型错误。
  • IDE支持:增强代码补全和错误提示(如VS Code的strict模式)。
注意事项
  • Python是动态类型语言,注释不会影响运行时行为。
  • 复杂类型可使用from __future__ import annotations延迟解析(Python 3.7+)。
  • 泛型变量名需一致(如T = TypeVar("T"))。

通过合理使用类型注释,可以显著提升代码的健壮性和开发效率。