082 typing module

typing module

  • We define a parameter of the function, but we will call him when in the back, they will need to pass parameters to forget what type, if the return is the result of arithmetic operation, the program will error.
def func(a,b):
    return a+b
res = fun('10',20)
print(res)

must be str, not int (the program will be error, we pass numeric parameters can only be carried out when the numerical arithmetic should)

1. typing module

  • typing module can help us solve this problem, it can then we define parameters for each of the rear position parameter: the received value + type, a prompt to us, then pycharm, if we pass to the parameter is not typin type specified, then the received value will we crossed tips.

    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)]

  • But if we pass parameters is to use the type specified in typing, we use the list to receive parameters of time, regardless of whether we follow the type prescribed typing to traditional values, we finally return to the list, the program then the current function returns the result of time when not being given

    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))

  • Then the next time a function call when the current function returns a value, it will generate an error.

    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 use

  1. typing can limit the type of function parameters
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 can limit the return value of the function
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 may be limited by the type of the return value in the specific value

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)

  • When passing through the parameters: type "parameters type" parameter declaration form;
  • The results returned by - Type "> Result Type" in the form of declaration of results.
  • If the type parameter is incorrect pycharm will be reminded at the time of the call, but will not affect the operation of the program.
  • For lists such as list, provision may also be made more specific number, such as: "-> List [str]", returns a list of predetermined, and the element is a string.
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 main provider of data types

  1. int, long, float: integer, long integer, floating point
  2. bool, str: Boolean, string type
  3. List, Tuple, Dict, Set: lists, tuples, dictionaries, collections
  4. Generator: the type of generator
  5. Iterable: iterator type can be
  6. Iterator: iterator type
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

Guess you like

Origin www.cnblogs.com/XuChengNotes/p/11402840.html