【Python】Python中的类型注释(Type Annotations)

【Python】Python中的类型注释(Type Annotations)

1.前言

Python是一种动态特性语言,即无须程序员显示指定变量的数据类型,给变量赋什么值变量就是什么数据类型。但是在程序员维护大型的项目的时候,面对陌生的变量若不知道变量数据类型便难以写代码进行调试,所以Python在3.5版本开始逐步引入了Type Annotations,在Python3.8之后可以直接使用Type Annotations,在之前的版本需要使用

from __future__ import annotations

才能够正常使用Type Annotations

2.变量的类型注释

用法为变量名: 数据类型

# 变量 x 的类型为整数
x: int = 5

# 变量 name 的类型为字符串
name: str = "John"

3.函数的返回值类型注释

用法为def func(变量名:数据类型, ...) -> 返回值数据类型:

def add_numbers(a: int, b: int) -> int:
    return a + b

4.复杂数据类型的注释

from typing import List, Dict

# 变量 numbers 的类型为整数列表
numbers: List[int] = [1, 2, 3]

# 变量 person 的类型为字典,包含字符串键和整数值
person: Dict[str, int] = {
    
    'age': 25, 'height': 180}

5.自定义数据类型的注释

class Point:
    def __init__(self, x: float, y: float) -> None:
        self.x = x
        self.y = y

# 变量 p 的类型为 Point
p: Point = Point(1.0, 2.0)

猜你喜欢

转载自blog.csdn.net/qq_44940689/article/details/134782959