zoukankan      html  css  js  c++  java
  • 082 typing模块

    typing模块

    • 我们定义一个有参的函数,但是我们会在后面调用他的时候,自己会忘了需要传什么类型的参数,如果返回的是算数运算的结果的话,程序就会报错。
    def func(a,b):
        return a+b
    res = fun('10',20)
    print(res)
    

    must be str, not int(程序会进行报错,我们传的参数应该时数值型,才可以进行数值算数运算)

    1.使用typing模块

    • typing模块就可以帮我们解决这种问题,它可以再我们定义参数每一个位置形参的后面:+接收值的类型,来对我们进行一个提示,再pycharm里,如果我们传的参数不是typin给规定的类型的话,接收值会给我们进行划线提示。

      from typing import List,Dict,Tuple
      
      def func(a:str,b:bool,c:int,lt:list,dct:dict,tp:tuple):
          lis = [a,b,c,lt,dct,tp]
          return lis
      
      res = func('a',True,25,[1,2,3,4],{'b':20},(7,8))
      print(res)
      

      ['a', True, 25, [1, 2, 3, 4], {'b': 20}, (7, 8)]

    • 但是如果我们传的参数是利用typing规定的类型时,我们使用列表来接收参数的时候,不管我们是否按照typing规定的类型来传值,我们最后返回列表的时候,程序再当前函数返回结果的时候时不会报错的

      from typing import List,Dict,Tuple
      
      def func(a:str,b:bool,c:int,lt:list,dct:dict,tp:tuple):
          lis = [a,b,c,lt,dct,tp]
          return lis
      
      # lt = 1
      res = func('a',True,25,1,{'b':20},(7,8))
      print(res)
      # ('a', True, 25, 1, {'b': 20}, (7, 8))程序再当前函数返回结果的时候时不会报错的,只是我们传的参数不规范
      

      ('a', True, 25, 1, {'b': 20}, (7, 8))

    • 再下一次函数调用当前函数返回值的时候,就会产生错误。

      from typing import Generator,Iterable,Iterator
      
      def func(i: int, f: float, b: bool, lt: list, tup: tuple, dic: dict):
          lis = [a,b,c,lt,dct,tp]
          return lis
      a,b,c,lt,dct,tp = func(1,2,3,4,5,6) # 不错误,只是不规范
      
      def func1(lt):
          print(lt[4])# 这个时候程序会报错
      func1(lt)
      

      'int' object is not subscriptable

    2.typing的使用

    1. typing可以对函数参数类型进行限制
    from typing import List,Dict,Tuple
    
    def func(a:str,b:bool,c:int,lt:list,dct:dict,tp:tuple):
        lis = [a,b,c,lt,dct,tp]
        return lis
    
    res = func('a',True,25,[1,2,3,4],{'b':20},(7,8))
    print(res)
    

    ['a', True, 25, [1, 2, 3, 4], {'b': 20}, (7, 8)]

    1. typing可以对函数的返回值进行限制
    from typing import List,Dict,Tuple
    
    def func(a:str,b:bool,c:int,lt:list,dct:dict,tp:tuple)-> tuple:
        lis = [a,b,c,lt,dct,tp]
        return tuple(lis)
    
    res = func('a',True,25,[1,2,3,4],{'b':20},(7,8))
    print(res)
    

    ('a', True, 25, [1, 2, 3, 4], {'b': 20}, (7, 8))

    3.可以对返回值里具体的值进行类型限制

    from typing import List, Tuple, Dict
    
    
    def add(a: int, string: str, f: float,
            b: bool) -> Tuple[List, Tuple, Dict, bool]:
        list1 = list(range(a))
        tup = (string, string, string)
        d = {"a": f}
        bl = b
        return list1, tup, d, bl
    
    
    print(add(5, "hhhh", 2.3, False))
    

    ([0, 1, 2, 3, 4], ('hhhh', 'hhhh', 'hhhh'), {'a': 2.3}, False)

    • 在传入参数时通过"参数名:类型"的形式声明参数的类型;
    • 返回结果通过"-> 结果类型"的形式声明结果的类型。
    • 在调用的时候如果参数的类型不正确pycharm会有提醒,但不会影响程序的运行。
    • 对于如list列表等,还可以规定得更加具体一些,如:"-> List[str]”,规定返回的是列表,并且元素是字符串。
    from typing import List
    
    def func(a: int, string: str) -> List[int or str]:  # 使用or关键字表示多种类型
        list1 = []
        list1.append(a)
        list1.append(string)
        return list1
    

    3.typing主要提供数据类型

    1. int、long、float: 整型、长整形、浮点型
    2. bool、str: 布尔型、字符串类型
    3. List、 Tuple、 Dict、 Set:列表、元组、字典、集合
    4. Generator:生成器类型
    5. Iterable:可迭代类型
    6. Iterator:迭代器类型
    from typing import Generator,Iterable,Iterator
    
    def func(i: int, f: float, b: bool, lt: list, tup: tuple, dic: dict,g:Generator) -> tuple:
        lis = [i, f, b, lt, tup, dic]
        return tuple(lis)
    
    def ger():# 生成器
        yield
    
    res = func(1, 2, True, [1, 2], (1, 2), {'a': 1},ger())
    print(res)
    # (1, 2, True, [1, 2], (1, 2), {'a': 1})
    
    def func1(lt):
        print(lt)
        print(lt[0])
    func1(res)
    
    

    [1,2]

    1

  • 相关阅读:
    DIV+CSS 高手也得看的15个CSS常识
    dl,dt,dd标签 VS 传统table实现数据列表
    弥补Web开发缺陷实战 HTML5 中存储API
    50漂亮的后台管理界面模板
    提升你设计水平的CSS3新技术
    300+Jquery, CSS, MooTools 和 JS的导航菜单资源(总有一个适合你!)
    99款高质量免费HTML/CSS模板(看到了还行,推荐给大家)
    DIV+CSS:如何编写代码才能更有效率
    HTML5和CSS3开发工具资源汇总
    43个实例xHTML+CSS(DIV+CSS)网页及导航布局教程
  • 原文地址:https://www.cnblogs.com/XuChengNotes/p/11402840.html
Copyright © 2011-2022 走看看