当前位置 博文首页 > Python类型提示Type Hints示例详解

    Python类型提示Type Hints示例详解

    作者:小菠萝测试笔记 时间:2021-09-17 18:47

    目录
    • 为什么会有类型提示
      • 解决上述问题,类型提示
    • 类型提示分类
      • 变量类型提示
        • 没有使用类型提示
        • 使用了类型提示
        • 变量类型提示-元组打包
        • 变量类型提示-元组解包
        • 在类里面使用
      • 函数参数类型提示
        • 栗子一
        • 栗子二
      • 总结

        为什么会有类型提示

        Python是一种动态类型语言,这意味着我们在编写代码的时候更为自由,运行时不需要指定变量类型

        但是与此同时 IDE 无法像静态类型语言那样分析代码,及时给我们相应的提示,比如字符串的 split 方法

        def split_str(s):
            strs = s.split(",")
        

        由于不知道参数 s 是什么类型,所以当你敲  s.  的时候不会出现 split 的语法提示

        解决上述问题,类型提示

        Python 3.6 新增了两个特性 PEP 484 和 PEP 526

        • PEP 484:https://www.python.org/dev/peps/pep-0484/
        • PEP 526:https://www.python.org/dev/peps/pep-0526/

        帮助 IDE 为我们提供更智能的提示

        这些新特性不会影响语言本身,只是增加一点提示

        类型提示分类

        主要分两个

        • 变量提示:PEP 526 特性加的
        • 函数参数提示:PEP 484 特性加的

        变量类型提示

        没有使用类型提示

        想说明变量的数据类型只能通过注释

        # 'primes' is a list of integers
        primes = []  # type: List[int]
        
        # 'captain' is a string (Note: initial value is a problem)
        captain = ...  # type: str
        
        
        class Starship:
            # 'stats' is a class variable
            stats = {}  # type: Dict[str, int]

        使用了类型提示

        from typing import List, ClassVar, Dict
        
        # int 变量,默认值为 0
        num: int = 0
        
        # bool 变量,默认值为 True
        bool_var: bool = True
        
        # 字典变量,默认为空
        dict_var: Dict = {}
        
        # 列表变量,且列表元素为 int
        primes: List[int] = []
        
        
        class Starship:
            # 类变量,字典类型,键-字符串,值-整型
            stats: ClassVar[Dict[str, int]] = {}
        
            # 实例变量,标注了是一个整型
            num: int

        这里会用到 typing 模块,后面会再展开详解

        假设变量标注了类型,传错了会报错吗?

        from typing import List
        
        # int 变量,默认值为 0
        num: int = 0
        
        # bool 变量,默认值为 True
        bool_var: bool = True
        
        # 字典变量,默认为空
        dict_var: Dict = {}
        
        # 列表变量,且列表元素为 int
        primes: List[int] = []
        
        
        num = "123"
        bool_var = 123
        dict_var = []
        primes = ["1", "2"]
        
        print(num, bool_var, dict_var, primes)
        
        
        # 输出结果
        123 123 [] ['1', '2']

        它并不会报错,但是会有 warning,是 IDE 的智能语法提示

        所以,这个类型提示更像是一个规范约束,并不是一个语法限制

        变量类型提示-元组打包

        # 正常的元组打包
        a = 1, 2, 3
        
        # 加上类型提示的元组打包
        t: Tuple[int, ...] = (1, 2, 3)
        print(t)
        
        t = 1, 2, 3
        print(t)
        
        # py3.8+ 才有的写法
        t: Tuple[int, ...] = 1, 2, 3
        print(t)
        
        t = 1, 2, 3
        print(t)
        
        
        # 输出结果
        (1, 2, 3)
        (1, 2, 3)
        (1, 2, 3)
        (1, 2, 3)

        为什么要加 ...

        不加的话,元组打包的时候,会有一个 warning 提示

        变量类型提示-元组解包

        # 正常元组解包
        message = (1, 2, 3)
        a, b, c = message
        print(a, b, c)  # 输出 1 2 3
        
        # 加上类型提示的元组解包
        header: str
        kind: int
        body: Optional[List[str]]
        
        # 不会 warning 的栗子
        header, kind, body = ("str", 123, ["1", "2", "3"])
        
        # 会提示 warning 的栗子
        header, kind, body = (123, 123, ["1", "2", "3"])

        Optional 会在后面讲 typing 的时候详解

        在类里面使用

        class BasicStarship:
            captain: str = 'Picard'               # 实例变量,有默认值
            damage: int                           # 实例变量,没有默认值
            stats: ClassVar[Dict[str, int]] = {}  # 类变量,有默认值

        ClassVar

        • 是 typing 模块的一个特殊类
        • 它向静态类型检查器指示不应在类实例上设置此变量

        函数参数类型提示

        不仅提供了函数参数列表的类型提示,也提供了函数返回的类型提示

        栗子一

        # 参数 name 类型提示 str,而函数返回值类型提示也是 str
        def greeting(name: str) -> str:
            return 'Hello ' + name

        栗子二

         def greeting(name: str, obj: Dict[str, List[int]]) -> None:
            print(name, obj)

        总结

        jsjbwy
        下一篇:没有了