文章目录
- 前言
- 简介
- 一、函数参数的类型指定
- 1. 基本类型提示
- 2. 默认参数
- 3. 可变参数
- 4. 联合类型(Union)
- 5. 可选类型(Optional)
- 6. 复杂类型
- 二、返回值的类型指定
- 1. 基本返回类型
- 2. 无返回值(None)
- 3. 返回多个值(Tuple)
- 4. 生成器(Generator)
- 三、高级类型提示用法
- 1. 类型别名(Type Aliases)
- 2. 泛型(Generics)
- 3. 可调用对象(Callable)
- 4. NewType
- 四、工具支持与检查
- 1. 静态类型检查(mypy)
- 2. IDE支持
- 五、综合示例
- 六、注意事项
- 运行时无强制检测
- 兼容性
- 动态类型优势
- 通过合理使用类型提示
- 七、总结
前言
本文仅仅简单介绍了Python中函数参数的提前指明的使用。
简介
在Python中,类型提示(Type Hints)用于明确函数参数和返回值的预期类型,提升代码可读性和维护性,并支持静态类型检查工具(如mypy)。以下是详细说明及示例代码:
一、函数参数的类型指定
1. 基本类型提示
直接在参数后添加类型注解:
def greet(name: str, age: int) -> None:
print(f"Hello, {name}. You are {age} years old.")
2. 默认参数
在默认值前添加类型注解:
def add(a: int, b: int = 0) -> int:
return a + b
3. 可变参数
*args:使用Tuple或Iterable:
def sum_numbers(*args: float) -> float:
return sum(args)
**kwargs:使用Dict指定键值类型:
def print_kwargs(**kwargs: str) -> None:
for key, value in kwargs.items():
print(f"{key}: {value}")
4. 联合类型(Union)
允许多种可能的类型(Python 3.10+ 可使用 | 语法):
from typing import Union
def parse_input(value: Union[int, str]) -> int:
return int(value)
#Python 3.10+ 简化写法
def parse_input(value: int | str) -> int:
return int(value)
5. 可选类型(Optional)
表示参数可以是某类型或None:
from typing import Optional
def find_user(name: str) -> Optional[str]:
if name == "admin":
return "Admin User"
return None
6. 复杂类型
列表、字典:
from typing import List, Dict
def process_items(items: List[str], prices: Dict[str, float]) -> None:
for item in items:
print(f"Item: {item}, Price: {prices.get(item, 0.0)}")
自定义类:
class User:
def __init__(self, name: str):
self.name = name
def create_user(name: str) -> User:
return User(name)
二、返回值的类型指定
1. 基本返回类型
直接指定返回值类型:
def add(a: int, b: int) -> int:
return a + b
2. 无返回值(None)
明确函数没有返回值:
def log_message(message: str) -> None:
print(f"[LOG] {message}")
3. 返回多个值(Tuple)
使用Tuple指定多个返回值的类型:
from typing import Tuple
def split_name(full_name: str) -> Tuple[str, str]:
first, last = full_name.split()
return first, last
4. 生成器(Generator)
指定生成器的产出值、发送值和返回值类型:
from typing import Generator
def count_up_to(n: int) -> Generator[int, None, None]:
count = 1
while count <= n:
yield count
count += 1
三、高级类型提示用法
1. 类型别名(Type Aliases)
简化复杂类型声明:
from typing import List, Tuple
Coordinates = List[Tuple[float, float]]
def plot_points(points: Coordinates) -> None:
for x, y in points:
print(f"Plotting at ({x}, {y})")
2. 泛型(Generics)
使用TypeVar定义泛型类型:
from typing import TypeVar, List
T = TypeVar('T')
def first_element(items: List[T]) -> T:
return items[0]
3. 可调用对象(Callable)
标注回调函数的类型:
from typing import Callable
def on_event(callback: Callable[[str, int], None]) -> None:
callback("click", 100)
4. NewType
创建更明确的类型:
from typing import NewType
UserId = NewType("UserId", int)
def get_user(user_id: UserId) -> str:
return f"User {user_id}"
四、工具支持与检查
1. 静态类型检查(mypy)
安装与使用:
pip install mypy
mypy your_script.py
2. IDE支持
PyCharm/VSCode:自动补全和类型错误提示。
Jupyter Notebook:部分支持类型提示。
五、综合示例
from typing import Union, List, Optional, Tuple
#参数类型:联合类型 + 默认参数
def format_data(
data: Union[List[int], str],
prefix: str = "Data: "
) -> Optional[str]:
if isinstance(data, list):
return prefix + ", ".join(map(str, data))
elif isinstance(data, str):
return prefix + data
return None
#返回值类型:Tuple
def analyze_numbers(numbers: List[float]) -> Tuple[float, float]:
avg = sum(numbers) / len(numbers)
max_val = max(numbers)
return avg, max_val
#泛型函数
from typing import TypeVar
T = TypeVar("T")
def filter_list(items: List[T], condition: Callable[[T], bool]) -> List[T]:
return [item for item in items if condition(item)]
#使用示例
if __name__ == "__main__":
print(format_data([1, 2, 3])) # 输出: Data: 1, 2, 3
avg, max_val = analyze_numbers([10.5, 20.3, 15.2])
print(f"Average: {avg}, Max: {max_val}") # 输出: Average: 15.333..., Max: 20.3
六、注意事项
运行时无强制检测
运行时无强制检查:类型提示不会影响代码执行,需依赖工具(如mypy)检查。
兼容性
兼容性:Python 3.5+ 支持基础类型提示,部分高级特性需更高版本。
动态类型优势
动态类型优势:类型提示不破坏Python的灵活性,可选择性使用。
通过合理使用类型提示
通过合理使用类型提示,可以显著提升代码的可维护性和团队协作效率。
七、总结
以上就是今天要讲的内容,本文仅仅简单介绍了Python中函数参数的提前指明的使用。