Python类型提示Type Hints示例详解

时间:2024-04-30 23:10:05 来源:网络 浏览:50次
目录为什么会有类型提示解决上述问题,类型提示
类型提示分类变量类型提示没有使用类型提示使用了类型提示变量类型提示-元组打包变量类型提示-元组解包在类里面使用函数参数类型提示栗子一栗子二总结

为什么会有类型提示

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 integersprimes = [] # type: List[int]# ’captain’ is a string (Note: initial value is a problem)captain = ... # type: strclass Starship: # ’stats’ is a class variable stats = {} # type: Dict[str, int]使用了类型提示

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

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

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

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

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

Python类型提示Type Hints示例详解

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

变量类型提示-元组打包

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

为什么要加 ...

Python类型提示Type Hints示例详解

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

变量类型提示-元组解包

# 正常元组解包message = (1, 2, 3)a, b, c = messageprint(a, b, c) # 输出 1 2 3# 加上类型提示的元组解包header: strkind: intbody: 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,而函数返回值类型提示也是 strdef greeting(name: str) -> str: return ’Hello ’ + name栗子二

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

总结

到此这篇关于Python类型提示Type Hints的文章就介绍到这了,更多相关Python类型提示Type Hints内容请搜索ABC学习网以前的文章或继续浏览下面的相关文章希望大家以后多多支持ABC学习网!

(window.slotbydup = window.slotbydup || []).push({id: "u6915441",container: "_5rmj5io5v3i",async: true});
评论
评论
发 布