主页
  • 主页
  • 分类
  • 热文
  • 教程
  • 面试
  • 标签
Python

Python 基础

Python 主页
Python 概述
Python 历史
Python 功能
Python 与 C++
Python Hello World
Python 应用领域
Python 解释器及其模式
Python 环境设置
Python 虚拟环境
Python 语法
Python 变量
Python 数据类型
Python 类型转换
Python Unicode 系统
Python 文字
Python 运算符
Python 算术运算符
Python 比较运算符
Python 赋值运算符
Python 逻辑运算符
Python 位运算符
Python 成员运算符
Python 身份运算符
Python 运算符优先级
Python 注释
Python 用户输入
Python 数字
Python 布尔值

Python 控制语句

Python 控制流
Python 决策
Python if 语句
Python if-else 语句
Python 嵌套 if 语句
Python match-case 语句
Python 循环
Python For 循环
Python for-else 循环
Python while 循环
Python break 语句
Python Continue 语句
Python pass 语句
Python 嵌套循环

Python 函数和模块

Python 函数
Python 默认参数
Python 关键字参数
Python 关键字专用参数
Python 位置参数
Python 仅限位置参数
Python 任意或可变长度参数
Python 变量作用域
Python 函数注释
Python 模块
Python 内置函数

Python 字符串

Python 字符串
Python 字符串切片
Python 字符串修改
Python 字符串连接
Python 字符串格式化
Python 转义字符
Python 字符串方法
Python 字符串练习

Python 列表

Python 列表
Python 访问列表项
Python 更改列表项
Python 添加列表项
Python 删除列表项
Python 循环列表
Python 列表推导式
Python 排序列表
Python 复制列表
Python 合并列表
Python 列表方法
Python 列表练习

Python 元组

Python 元组
Python 访问元组项
Python 更新元组
Python 解包元组项
Python 循环元组
Python 合并元组
Python 元组方法
Python 元组练习

Python 集合

Python 集合
Python 访问集合项
Python 添加集合项
Python 删除集合项
Python 循环集合
Python 合并集合
Python 复制集合
Python 集合运算符
Python 集合方法
Python 集合练习

Python 字典

Python 字典
Python 访问字典项
Python 更改字典项
Python 添加字典项
Python 移除字典项
Python 字典视图对象
Python 循环字典
Python 复制字典
Python 嵌套字典
Python 字典方法
Python 字典练习

Python 数组

Python 数组
Python 访问数组项
Python 添加数组项
Python 移除数组项
Python 循环数组
Python 复制数组
Python 反转数组
Python 排序数组
Python 合并数组
Python 数组方法
Python 数组练习

Python 文件处理

Python 文件处理
Python 文件写入
Python 文件读取
Python 重命名和删除文件
Python 目录
Python 文件方法
Python 文件/目录方法
Python OS.Path 方法

Python 面向对象编程

Python OOP 概念
Python 类和对象
Python 类属性
Python 类方法
Python 静态方法
Python 构造函数
Python 访问修饰符
Python 继承
Python 多态
Python 方法重写
Python 方法重载
Python 动态绑定
Python 动态类型
Python 抽象
Python 封装
Python 接口
Python 包
Python 内部类
Python 匿名类和对象
Python 单例类
Python 包装器类
Python 枚举
Python 反射

Python 错误和异常

Python 语法错误
Python 异常处理
Python Try-Except
Python Try-Finally
Python 抛出异常
Python 异常链
Python 嵌套 try
Python 用户定义异常
Python 日志记录
Python 断言
Python 内置异常

Python 多线程

Python 多线程
Python 线程生命周期
Python 创建线程
Python 启动线程
Python 合并线程
Python 命名线程
Python 线程调度
Python 线程池
Python 主线程
Python 线程优先级
Python 守护线程
Python 线程同步

Python 同步

Python 线程间通信
Python 死锁
Python 中断线程

Python 网络

Python 网络编程
Python 套接字编程
Python URL 处理
Python 泛型

Python 杂项

Python Date and Time
Python math模块
Python 迭代器
Python 生成器
Python 闭包
Python 装饰器
Python 递归
Python 正则表达式
Python Pip
Python 数据库访问
Python 弱引用
Python 序列化
Python 模板技术
Python 输出格式化
Python 性能测量
Python 数据压缩
Python 通用网关接口
Python XML 处理
Python 用户界面(GUI)
Python 命令行参数
Python Docstrings
Python JSON
Python 发送电子邮件
Python 进一步扩展
Python 工具/实用程序
Python GUI

Python 高级概念

Python 抽象基类
Python 自定义异常
Python 高阶函数
Python 对象的内部机制
Python 内存管理
Python 元类
Python 元编程
Python 模拟与桩
Python 猴子补丁
Python 信号处理
Python 类型提示
Python 进行自动化
Python Humanize包
Python 上下文管理器
Python 协程
Python 描述符
Python 内存泄漏
Python 不可变数据结构

基础

Python 主页
Python 概述
Python 历史
Python 功能
Python 与 C++
Python Hello World
Python 应用领域
Python 解释器及其模式
Python 环境设置
Python 虚拟环境
Python 语法
Python 变量
Python 数据类型
Python 类型转换
Python Unicode 系统
Python 文字
Python 运算符
Python 算术运算符
Python 比较运算符
Python 赋值运算符
Python 逻辑运算符
Python 位运算符
Python 成员运算符
Python 身份运算符
Python 运算符优先级
Python 注释
Python 用户输入
Python 数字
Python 布尔值

控制语句

Python 控制流
Python 决策
Python if 语句
Python if-else 语句
Python 嵌套 if 语句
Python match-case 语句
Python 循环
Python For 循环
Python for-else 循环
Python while 循环
Python break 语句
Python Continue 语句
Python pass 语句
Python 嵌套循环

函数和模块

Python 函数
Python 默认参数
Python 关键字参数
Python 关键字专用参数
Python 位置参数
Python 仅限位置参数
Python 任意或可变长度参数
Python 变量作用域
Python 函数注释
Python 模块
Python 内置函数

字符串

Python 字符串
Python 字符串切片
Python 字符串修改
Python 字符串连接
Python 字符串格式化
Python 转义字符
Python 字符串方法
Python 字符串练习

列表

Python 列表
Python 访问列表项
Python 更改列表项
Python 添加列表项
Python 删除列表项
Python 循环列表
Python 列表推导式
Python 排序列表
Python 复制列表
Python 合并列表
Python 列表方法
Python 列表练习

元组

Python 元组
Python 访问元组项
Python 更新元组
Python 解包元组项
Python 循环元组
Python 合并元组
Python 元组方法
Python 元组练习

集合

Python 集合
Python 访问集合项
Python 添加集合项
Python 删除集合项
Python 循环集合
Python 合并集合
Python 复制集合
Python 集合运算符
Python 集合方法
Python 集合练习

字典

Python 字典
Python 访问字典项
Python 更改字典项
Python 添加字典项
Python 移除字典项
Python 字典视图对象
Python 循环字典
Python 复制字典
Python 嵌套字典
Python 字典方法
Python 字典练习

数组

Python 数组
Python 访问数组项
Python 添加数组项
Python 移除数组项
Python 循环数组
Python 复制数组
Python 反转数组
Python 排序数组
Python 合并数组
Python 数组方法
Python 数组练习

文件处理

Python 文件处理
Python 文件写入
Python 文件读取
Python 重命名和删除文件
Python 目录
Python 文件方法
Python 文件/目录方法
Python OS.Path 方法

面向对象编程

Python OOP 概念
Python 类和对象
Python 类属性
Python 类方法
Python 静态方法
Python 构造函数
Python 访问修饰符
Python 继承
Python 多态
Python 方法重写
Python 方法重载
Python 动态绑定
Python 动态类型
Python 抽象
Python 封装
Python 接口
Python 包
Python 内部类
Python 匿名类和对象
Python 单例类
Python 包装器类
Python 枚举
Python 反射

错误和异常

Python 语法错误
Python 异常处理
Python Try-Except
Python Try-Finally
Python 抛出异常
Python 异常链
Python 嵌套 try
Python 用户定义异常
Python 日志记录
Python 断言
Python 内置异常

多线程

Python 多线程
Python 线程生命周期
Python 创建线程
Python 启动线程
Python 合并线程
Python 命名线程
Python 线程调度
Python 线程池
Python 主线程
Python 线程优先级
Python 守护线程
Python 线程同步

同步

Python 线程间通信
Python 死锁
Python 中断线程

网络

Python 网络编程
Python 套接字编程
Python URL 处理
Python 泛型

杂项

Python Date and Time
Python math模块
Python 迭代器
Python 生成器
Python 闭包
Python 装饰器
Python 递归
Python 正则表达式
Python Pip
Python 数据库访问
Python 弱引用
Python 序列化
Python 模板技术
Python 输出格式化
Python 性能测量
Python 数据压缩
Python 通用网关接口
Python XML 处理
Python 用户界面(GUI)
Python 命令行参数
Python Docstrings
Python JSON
Python 发送电子邮件
Python 进一步扩展
Python 工具/实用程序
Python GUI

高级概念

Python 抽象基类
Python 自定义异常
Python 高阶函数
Python 对象的内部机制
Python 内存管理
Python 元类
Python 元编程
Python 模拟与桩
Python 猴子补丁
Python 信号处理
Python 类型提示
Python 进行自动化
Python Humanize包
Python 上下文管理器
Python 协程
Python 描述符
Python 内存泄漏
Python 不可变数据结构

Python 类型提示


上一章 下一章

Python 类型提示是在 PEP 484 中引入的,目的是为动态类型的语言带来静态类型的好处。虽然类型提示不会在运行时强制类型检查,但它们提供了一种指定变量、函数参数和返回值预期类型的方法,这些可以通过如 mypy 等静态分析工具来检查。这增强了代码的可读性,方便了调试,并提高了代码的整体可维护性。

类型提示在 Python 中使用注解来表示函数参数、返回值和变量赋值的类型。

Python 的类型提示可以用来指定各种类型的类型,如基本数据类型、集合、复杂类型以及用户自定义类型。typing 模块提供了许多内置类型来表示这些不同的类型:

  • 基本数据类型
  • 集合类型
  • 可选类型
  • 联合类型
  • 任意类型
  • 类型别名
  • 泛型
  • 可调用类型
  • 文本类型
  • 新类型

让我们逐一详细地看看每一种类型。

基本数据类型

在 Python 中,当我们使用类型提示来指定基本类型时,可以直接使用类型的名称作为注解。

示例

下面是一个使用基本数据类型的示例:

from typing import Optional

# 整数类型
def calculate_square_area(side_length: int) -> int:
   return side_length ** 2

# 浮点数类型
def calculate_circle_area(radius: float) -> float:
   return 3.14 * radius * radius

# 字符串类型
def greet(name: str) -> str:
   return f"Hello, {name}"

# 布尔类型
def is_adult(age: int) -> bool:
   return age >= 18

# None 类型
def no_return_example() -> None:
   print("This function does not return anything")

# 可选类型 (int 或 None 的联合)
def safe_divide(x: int, y: Optional[int]) -> Optional[float]:
   if y is None or y == 0:
      return None
   else:
      return x / y

# 示例使用
print(calculate_square_area(5))        
print(calculate_circle_area(3.0))     
print(greet("Alice"))                 
print(is_adult(22))                   
no_return_example()                   
print(safe_divide(10, 2))             
print(safe_divide(10, 0))             
print(safe_divide(10, None))          

输出

执行上述代码我们将得到以下输出:

25
28.259999999999998
Hello, Alice
True
This function does not return anything
5.0
None
None

集合类型

在 Python 中,当我们处理列表、元组、字典等集合时,在类型提示中通常使用 typing 模块来指定集合类型。

示例

下面是使用集合类型的示例:

from typing import List, Tuple, Dict, Set, Iterable, Generator

# 整数列表
def process_numbers(numbers: List[int]) -> List[int]:
   return [num * 2 for num in numbers]

# 浮点数元组
def coordinates() -> Tuple[float, float]:
   return (3.0, 4.0)

# 字符串键整数值字典
def frequency_count(items: List[str]) -> Dict[str, int]:
   freq = {}
   for item in items:
      freq[item] = freq.get(item, 0) + 1
   return freq

# 字符串中的唯一字符集合
def unique_characters(word: str) -> Set[str]:
   return set(word)

# 整数可迭代对象
def print_items(items: Iterable[int]) -> None:
   for item in items:
      print(item)

# 生成器产生小于 n 的整数平方
def squares(n: int) -> Generator[int, None, None]:
   for i in range(n):
      yield i * i

# 示例使用
numbers = [1, 2, 3, 4, 5]
print(process_numbers(numbers))                   

print(coordinates())                            

items = ["apple", "banana", "apple", "orange"]
print(frequency_count(items))                    

word = "hello"
print(unique_characters(word))                   

print_items(range(5))                           

gen = squares(5)
print(list(gen))                                          

输出

执行上述代码我们将得到以下输出:

[2, 4, 6, 8, 10]
(3.0, 4.0)
{'apple': 2, 'banana': 1, 'orange': 1}
{'l', 'e', 'h', 'o'}
0
1
2
3
4
[0, 1, 4, 9, 16]

可选类型

在 Python 中,可选类型用于指示一个变量可以是某个指定类型或者 None。这对于函数可能不总是返回值或参数可以接受一个值或留空时特别有用。

示例

下面是一个使用可选类型的示例:

from typing import Optional

def divide(a: float, b: float) -> Optional[float]:
   if b == 0:
      return None
   else:
      return a / b

result1: Optional[float] = divide(10.0, 2.0)   # result1 将是 5.0
result2: Optional[float] = divide(10.0, 0.0)   # result2 将是 None

print(result1)  
print(result2)                                           

输出

执行上述代码我们将得到以下输出:

5.0
None

联合类型

Python 使用联合类型来允许一个变量接受不同类型的值。这对于函数或数据结构可以处理多种输入类型或产生不同类型输出的情况特别有用。

示例

下面是一个联合类型的示例:

from typing import Union

def square_root_or_none(number: Union[int, float]) -> Union[float, None]:
   if number >= 0:
      return number ** 0.5
   else:
      return None

result1: Union[float, None] = square_root_or_none(50)   
result2: Union[float, None] = square_root_or_none(-50)  

print(result1)  
print(result2)                                             

输出

执行上述代码我们将得到以下输出:

7.0710678118654755
None

任意类型

在 Python 中,任意类型 (Any) 是一种特殊的类型提示,表示一个变量可以是任何类型。它基本上禁用了对该变量或表达式的类型检查。对于在事先不知道值的类型或处理动态数据时,这可能是有用的。

示例

下面是一个使用 Any 类型的示例:

from typing import Any

def print_value(value: Any) -> None:
   print(value)

print_value(10)         
print_value("hello")    
print_value(True)       
print_value([1, 2, 3])  
print_value({'key': 'value'})                                           

输出

执行上述代码我们将得到以下输出:

10
hello
True
[1, 2, 3]
{'key': 'value'}

类型别名

Python 中的类型别名用于给现有类型提供替代名称。它们可以通过给复杂的类型注解或类型组合提供清晰的名字来使代码更容易阅读。这对于处理嵌套结构或长类型提示特别有帮助。

示例

下面是一个使用类型别名的示例:

from typing import List, Tuple

# 定义一个整数列表的类型别名
Vector = List[int]

# 定义一个坐标元组的类型别名
Coordinates = Tuple[float, float]

# 使用类型别名的函数
def scale_vector(vector: Vector, factor: float) -> Vector:
    return [int(num * factor) for num in vector]

def calculate_distance(coord1: Coordinates, coord2: Coordinates) -> float:
   x1, y1 = coord1
   x2, y2 = coord2
   return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5

# 使用类型别名
v: Vector = [1, 2, 3, 4]
scaled_v: Vector = scale_vector(v, 2.5)
print(scaled_v)  

c1: Coordinates = (3.0, 4.0)
c2: Coordinates = (6.0, 8.0)
distance: float = calculate_distance(c1, c2)
print(distance)                                             

输出

执行上述代码我们将得到以下输出:

[2, 5, 7, 10]
5.0

泛型

泛型类型创建能够处理任何类型的函数、类或数据结构,同时保持类型安全。typing 模块中的 TypeVar 和 Generic 构造使得这成为可能。它们对于制作能够处理各种类型而不影响类型检查的可复用组件特别有用。

示例

下面是一个泛型类型的示例:

from typing import TypeVar, List

# 定义一个类型变量 T
T = TypeVar('T')

# 泛型函数,返回列表的第一个元素
def first_element(items: List[T]) -> T:
   return items[0]

# 示例使用
int_list = [1, 2, 3, 4, 5]
str_list = ["apple", "banana", "cherry"]

first_int = first_element(int_list)      # first_int 将是 int 类型
first_str = first_element(str_list)      # first_str 将是 str 类型

print(first_int)    
print(first_str)                                              

输出

执行上述代码我们将得到以下输出:

1
apple

可调用类型

Python 中的 Callable 类型用于表明一个类型是函数或可调用对象。它位于 typing 模块中,并允许定义函数的参数类型和返回类型。这对于高阶函数特别有用。

示例

下面是一个使用 Callable 类型的示例:

from typing import Callable

# 定义一个函数,接受另一个函数作为参数
def apply_operation(x: int, y: int, operation: Callable[[int, int], int]) -> int:
   return operation(x, y)

# 示例函数作为参数传递
def add(a: int, b: int) -> int:
   return a + b

def multiply(a: int, b: int) -> int:
   return a * b

# 使用带有不同操作的 apply_operation 函数
result1 = apply_operation(5, 3, add)        # result1 将是 8
result2 = apply_operation(5, 3, multiply)   # result2 将是 15

print(result1)  
print(result2)                                                

输出

执行上述代码我们将得到以下输出:

8
15

文本类型

文本类型 (Literal) 用于指定一个值必须精确地等于一组预定义值中的一个。

示例

下面是一个示例:

from typing import Literal

def move(direction: Literal["left", "right", "up", "down"]) -> None:
   print(f"移动方向为 {direction}")

move("left")  # 合法
move("up")    # 合法                                     

输出

执行上述代码我们将得到以下输出:

移动方向为 left
移动方向为 up

新类型

NewType 是 typing 模块中的一个函数,它允许我们创建从现有类型派生的独特类型。这对于我们通过区分相同底层类型的不同用途来增加代码的安全性是有用的。例如,我们可能希望区分用户ID和产品ID,尽管它们都表示为整数。

示例

下面是一个示例:

from typing import NewType

# 创建新类型
UserId = NewType('UserId', int)
ProductId = NewType('ProductId', int)

# 定义使用新类型的函数
def get_user_name(user_id: UserId) -> str:
   return f"ID 为 {user_id} 的用户"

def get_product_name(product_id: ProductId) -> str:
   return f"ID 为 {product_id} 的产品"

# 示例使用
user_id = UserId(42)
product_id = ProductId(101)

print(get_user_name(user_id))   # 输出: ID 为 42 的用户
print(get_product_name(product_id))  # 输出: ID 为 101 的产品                                   

输出

执行上述代码我们将得到以下输出:

ID 为 42 的用户
ID 为 101 的产品
上一章 下一章
阅读号二维码

关注阅读号

联系二维码

联系我们

© 2024 Yoagoa. All rights reserved.

粤ICP备18007391号

站点地图