首页 > 其他 > 详细

类型注解

时间:2020-11-15 00:23:42      阅读:34      评论:0      收藏:0      [点我收藏+]

参考:https://blog.csdn.net/cainiao_python/article/details/98818428

python3.5中引入了类型注解(type hints),python3.6中进一步引入了变量注解(variable annotation),带来了许多方便。

typing模块(作为python内置模块可直接使用)
from typing import List, Tuple ...

  • List
    var: List[int or float] = [2,3.5]
    var: List[int, int, int] = [2,2,2]

  • Tuple
    按顺序说明了构成本元组元素的类型
    a:Tupel[int, int]=1,2

  • Dict,Mapping
    中括号内分别声明键名,键值的类型;Dict推荐使用注解返回类型,Mapping推荐使用注解参数
    def size(rec:Mapping[str, int])->Dict[str,int]:
    return {"width":rect["width"], "height":rect["height"]+10}

  • Set,AbstractSet
    Set推荐用于注解返回值类型,AbstarctSet推荐用于注解参数类型
    def demo(s:AbstractSet[int])->Set[int]:
    return set(s)

  • Sequence
    是collections.abc.Sequence的泛型,当不需要严格区分某变量是list类型还是tuple类型时可以采用泛化的类型Sequence,用法类似于List
    def square(elements:Sequence[int])->List[int]:
    return [x ** 2 for x in elements]

  • NoReturn
    用于注解没有返回值的方法的返回类型
    def test()->NoReturn:
    pass

  • Any
    一种特殊类型,可代表所有类型,所有无参数类型注解和返回类型注解的都会默认使用Any类型
    def add(a:Any, b:Any)->Any:
    return a+b

  • TypeVar
    可用于自定义兼容特定类型的变量的方法
    Args=TypeVar("Args",int, float,None)
    args=0
    def getArgs()->Args:
    return args

  • NewType
    可用于声明一些具有特殊含义的类型(起别名)的方法
    Gender=NewType("Gender",str)

  • Callable
    可调用类型,常用于注解一个方法。声明时需要按照Callable[[Arg1Type, Arg2Type, ...], ReturnType],将参数类型和返回值类型都注解出来
    def data(year:int, month:int, day:int)->str:
    return f‘{year}-{month}-{day}‘ //格式化字符串
    def get_data()->Callable[[int,int,int],str]:
    return data

  • Union
    类型选择中括号中其一
    多余的参数会被跳过;中括号中参数顺序会被忽略;仅有一个参数的联合类型等价于参数自身
    def process(fn:Union[str,Callable]):
    if isinstance(fn,str):
    pass
    elif isinstance(fn,Callable):
    fn()

  • Optional
    意为此参数可以为空或者是中括号中的类型,并不代表可以不传递参数,而是指参数可以传为None
    def judge(result:bool)->Optional[str]:
    if !result:
    return "Error"

  • Generator
    中括号中紧跟三个参数,分别代表[YieldType, SendType, ReturnType]
    def infinite_stream(start:int)->Generator[int,None,None]:
    while True:
    yield start
    start+=1

类型注解

原文:https://www.cnblogs.com/ShineMiao/p/13975040.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!