Python基础-24 类型标注

24 类型标注

24.1 Python中的数据类型

在Python中有很多 数据类型,比较常见如下所示:

整型 浮点型 字符串 列表 元组 字典 集合 布尔 int float str list tuple dict set bool

因Python是 弱类型语言,所以在实际写代码时,一般不去 声明定义参数的类型。示例如下:

def welcome(city):
   print(f"welcome to {city}")

以上代码非常简单,就是输出一行欢迎标语。而在大家看到这个代码,也都 默认了city是一个字符串类型(str)。

现在我们来改造一下代码,将传入的city参数全部变为大写,代码如下所示:

def welcome(city):
   print(f"welcome to {city.upper()}")

以上代码在传入的city为字符串类型时,一切正常,但如果传入的是 非字符串类型就会报错,例如传入 123,便会出现如下所示的报错

AttributeError: 'int' object has no attribute 'upper'

24.2 指定类型

24.2.1 指定变量类型

24.2.1.1 指定变量类型

针对以上问题,Python 3.5中引入了 typing包,推荐使用 类型标注,并且IDE会检查类型,让Python看起来有点像静态语言的感觉。

那么如何指定变量类型呢?您只需要在变量名后面加上:type,如下图所示:

[En]

So how do you specify the variable type? You only need to put * : type * after the variable name, as shown below:

def welcome(city:str):
   print(f"welcome to {city.upper()}")
24.2.1.2 变量类型声明的好与坏

以前使用过强类型语言的人可能会认为变量类型声明是理所当然的。但它可能不适用于弱类型语言,但它确实有一些优势。

[En]

Variable type declarations may be taken for granted by people who have previously used a strongly typed language. But it may not be used to weakly typed languages, but it does have some advantages.

  • 以上面代码为例,如果定义为str类型,而实际传入为int时,PyCharm会进行相应的提示,不能这样做,如下所示:

Python基础-24 类型标注
  • PyCharm会有更多提示

在Python中,str类型的数据会有很多方法,而在指定数据类型后,PyCharm则会有更多提示,如下所示:

Python基础-24 类型标注
  • 代码易于阅读,可以更快地知道需要传入什么类型的数据和返回什么类型的数据。
    [En]

    it is easy to read the code, and you can know more quickly what type of data needs to be passed in and the type of data returned.*

指定变量的数据类型也有一些缺点,如下所示:

[En]

There are also some disadvantages when specifying the data type of a variable, as follows:

  • 写代码的时候,需要写更多的代码,看起来不是那么流畅。
    [En]

    when writing code, you need to write more code, which doesn’t look so smooth.*

  • 虽然指定的数据类型,但也仅仅是方便查看,并没有规定死变量类型,如指定为str类型,但传入int,依然可以运行代码,没有在 运行层面进行检查

24.2.2 指定返回值类型

在Python里面,方法/函数都是有返回值的,那么使用类型标的话,可以直接 方法/函数末尾冒号之前添加 ->类型,示例如下所示:

def welcome(city:str)->str:
   return city.upper()

这样做的好处跟之前示例一样,IDE可以更加智能提示,防止编写代码出错,如下所示:

Python基础-24 类型标注

指定类型不会影响编译结果,但有很多好处,如下所示:

[En]

Specifying a type does not affect the compilation result, but there are many benefits, as follows:

  • 提高开发效率
  • 降低出错率
  • 阅读代码更友好

24.3 typing包

24.3.1 typing作用

主要作用如下所示:

  • 类型检查以防止运行时参数和返回值类型不一致
    [En]

    Type checking to prevent run-time parameter and return value type discrepancies*

  • 添加开发文档说明,便于调用者快速查看传入和返回的数据类型
    [En]

    add instructions as development documentation to make it easy for callers to quickly view incoming and returned data types*

  • 加入模块后,程序运行不受影响,只是提醒
    [En]

    after joining the module, the operation of the program will not be affected, only a reminder*

typing模块只有在Python 3.5 以上版本中才可以使用,PyCharm支持typing检查

24.3.2 typing包常见数据类型

类型 备注 int int str str List 列表,也可以使用list List[类型] 指定列表中存放的数据类型 Tuple 元组,也可以使用tuple Tuple[类型] 指定元组中存放的数据类型 Set 集合,也可以使用set Set[类型] 指定集合中存放的数据类型 Dict 字典,也可以使用dict Dict[类型1,类型2] key为类型1,value为类型2的字典 Sequence[类型] 指定序列中存放的数据类型 NoReturn 表示无返回类型 Any 任意类型 TypeVar 自定义兼容特定类型的变量 Union[类型1,类型2] 联合类型,可以接受类型1或类型2 Optional[类型] 参数可以为空或已经声明的类型

常见的类型如上表格表示,如果需要使用List,Set,Dict,Union则需要导入 typing

from typing import List,Set,Dict

24.3.3 typing包常见数据类型用法

  • *List

List:列表,是list的泛型,基本等同于list,其后紧跟一个方括号,里面代表了构成这个列表的元素类型,示例如下所示:

from typing import List

基本声明
listSample:List[int or str]=[1,"Surpass"]
嵌套声明
listSample:List[List[int]]=[[1,2],[3,4]]
  • *Tuple

Tuple:元组,是 tuple 的泛型,其后紧跟一个方括号,方括号中按照顺序声明了构成本元组的元素类型,如 Tuple[X, Y] 代表了构成元组的第一个元素是 X 类型,第二个元素是 Y 类型,示例如下所示:

from typing import Tuple

personInfo:Tuple[str,int,float,str]=("Surpass",28,62.33,"Shanghai")
  • *Set/AbstractSet

Set(集合)是set 的泛型,AbstractSet是 collections.abc.Set 的泛型。根据官方文档, Set 推荐用于注解返回类型,AbstractSet 用于注解参数,使用方法是后面跟一个中括号,里面声明集合中元素的类型,示例如下所示:

from typing import Set,AbstractSet

def SetSample(s:AbstractSet[int]) -> Set[int]:
    return  set(s)
  • *Dict/Mapping

Dict(字典)是 dict 的泛型,Mapping(映射)是 collections.abc.Mapping 的泛型。根据官方文档, Dict推荐用于注解返回类型,Mapping 推荐用于注解参数。使用方法都是其后跟一个中括号,中括号内分别声明键名、键值的类型,示例如下所示:

from typing import Dict,Mapping

def DictSample(personInfo:Mapping[str,str])->Dict[str,str]:
    return {"name":personInfo["name"],"location":personInfo["location"]}
  • *Sequence

Sequence是 collections.abc.Sequence 的泛型,在某些情况下,我们可能并不需要严格区分一个变量或参数到底是列表类型还是元组类型,则可以使用一个更为泛化的类型,叫做 Sequence,其用法类似于List,示例如下所示:

from typing import Sequence,List

def Square(ele:Sequence[int])->List[int]:
    return [i**2 for i in ele]
  • *NoReturn

当一个方法没有返回结果时,为了注解它的返回类型,我们可以将其注解为 NoReturn,示例如下所示:

from typing import NoReturn

def hello(word:str)->NoReturn:
    print(word.title())
  • *Any

Any是一种特殊的类型,它可以代表所有任意类型,静态类型检查器的所有类型都与 Any 类型兼容,所有的无参数类型注解和返回类型注解的都会默认使用 Any 类型。以下示例两种是完全等价相同的

from typing import Any

def hello(word):
    return word.title()

def hello(word:Any)->Any:
    return word.title()
  • *TypeVar

TypeVar可以用来 自定义兼容特定类型的变量,比如有的变量声明为int、float、str都是符合要求的,实际就是代表任意的数字或者字符串都是可以的,其他的类型则不可以。例如一个人的身高,便可以使用 int 或 float 或 None 来表示,但不能用 dict 来表示,所以可以这么声明:

from typing import TypeVar

Height=TypeVar(int,float,None)

def getHeight(height)->Height:
    return height
  • *NewType

NewType,我们可以借助于其来声明一些具有特殊含义的类型,如前面Tuple示例,需要用来定义一个Person信息,但从表面上声明为Tuple不太直观,因此可以借助NewType来进行声明。示例如下所示:

from typing import NewType,Tuple

personInfo=NewType("PersonInfo",Tuple[str,int,float,str])

person=personInfo(("Surpass",28,62.33,"Shanghai"))

示例中person就是一个tuple类型,跟其他tuple类型一样进行操作

  • *Union

Union(联合类型),Union[类型1,类型2] 代表要么是类型1类型,要么是类型2 类型。联合类型的联合类型等价于展平后的类型:

Union[Union[int, str], float] == Union[int, str, float]

只有一个参数的联合类型等同于参数本身,如下例所示:

[En]

The union type of only one parameter is equivalent to the parameter itself, as shown in the following example:

Union[int] == int

如果存在相同类型,将取消处理,如下例所示:

[En]

If the same type exists, it will be dereprocessed, as shown in the following example:

Union[int, str, int] == Union[int, str]

比较联合类型时,忽略参数顺序,如下例所示:

[En]

When comparing federated types, the parameter order is ignored, as shown in the following example:

Union[int, str] == Union[str, int]
from typing import Union

def getType(params:Union[int,str,float])->str:
    if isinstance(params,int):
        return f"{params} type is int"
    elif isinstance(params,float):
        return f"{params} type is float"
    elif isinstance(params,str):
        return f"{params} type is str"
    else:
        return f"{params} type is unknown"
  • *Optional

Optional意思是说这个 参数可以为空或已经声明的类型,即 Optional[类型1] 等价于 Union[类型1, None]

需要注意的是这个并不等价于可选参数,当它作为参数类型注解的时候,不代表这个参数可以不传递了,而是说这个参数可以传为 None。

from typing import Optional

def getInfo(data:Optional[int])->Optional[str]:
    if isinstance(data,int):
        return f"INFO - {data} type is int"
    elif data is None:
        return f"WARNING -  {data} type is None"
    else:
        return f"ERROR - {data} type is not int,"

原文地址:https://www.jianshu.com/p/5b135f8dec0d

本文同步在微信订阅号上发布,如各位小伙伴们喜欢我的文章,也可以关注我的微信订阅号:woaitest,或扫描下面的二维码添加关注:

Python基础-24 类型标注

Original: https://www.cnblogs.com/surpassme/p/16545609.html
Author: Surpassme
Title: Python基础-24 类型标注

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/498911/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球