Python -类型提示 Type HintsPython -类型提示 Type HintsPython -类型提示 Type HintsPython -类型提示 Type Hints
  • 首页
  • 博客
  • 文件
  • 书签
  • 分析
  • 登录
Search
Generic filters

Python -类型提示 Type Hints

Published by admin at 2022年4月10日
Categories
  • Python
Tags

为什么会有类型提示

  • Python是一种动态类型语言,这意味着我们在编写代码的时候更为自由,运行时不需要指定变量类型
  • 但是与此同时 IDE 无法像静态类型语言那样分析代码,及时给我们相应的提示,比如字符串的 split 方法

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

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

 

解决上述问题,类型提示

Python 3.5、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 模块,typing 是在 python 3.5 才有的模块

常用类型提示

  • int,long,float: 整型,长整形,浮点型;
  • bool,str: 布尔型,字符串类型;
  • List, Tuple, Dict, Set:列表,元组,字典, 集合;
  • Iterable,Iterator:可迭代类型,迭代器类型;
  • Generator:生成器类型;

前两行小写的不需要 import,后面三行都需要通过 typing 模块 import

 

类型别名

https://www.cnblogs.com/poloyy/p/15153883.html 

 

NewType

https://www.cnblogs.com/poloyy/p/15153886.html 

 

Callable

https://www.cnblogs.com/poloyy/p/15154008.html

 

TypeVar 泛型

https://www.cnblogs.com/poloyy/p/15154196.html

 

Any Type

https://www.cnblogs.com/poloyy/p/15158613.html

 

Union

https://www.cnblogs.com/poloyy/p/15170066.html

 

Optional

https://www.cnblogs.com/poloyy/p/15170297.html

发表回复 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Categories

  • 猫
  • Python
  • MySQL
  • Django
  • Html/CSS
  • JavaScript
  • Vue
  • RegExp
  • php
  • Practice
  • Virtualization
  • Linux
  • Windows
  • Android
  • NAS
  • Software
  • Hardware
  • Network
  • Router
  • Office
  • WordPress
  • SEO
  • English
  • Games
  • Recipes
  • living
  • Memorandum
  • Essays
  • 未分类

归档

©2015-2022 Alaica Blog support@alaica.com