075 typing模塊

typing模塊

  • 咱們定義一個有參的函數,可是咱們會在後面調用他的時候,本身會忘了須要傳什麼類型的參數,若是返回的是算數運算的結果的話,程序就會報錯。
def func(a,b):
    return a+b
res = fun('10',20)
print(res)

must be str, not int(程序會進行報錯,咱們傳的參數應該時數值型,才能夠進行數值算數運算)python

1.使用typing模塊

  • typing模塊就能夠幫咱們解決這種問題,它能夠再咱們定義參數每個位置形參的後面:+接收值的類型,來對咱們進行一個提示,再pycharm裏,若是咱們傳的參數不是typin給規定的類型的話,接收值會給咱們進行劃線提示。app

    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規定的類型來傳值,咱們最後返回列表的時候,程序再當前函數返回結果的時候時不會報錯的code

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

  • 再下一次函數調用當前函數返回值的時候,就會產生錯誤。字符串

    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 subscriptablepycharm

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

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

3.能夠對返回值裏具體的值進行類型限制class

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

相關文章
相關標籤/搜索