python 學習彙總43:typing-型別檢查(入門基礎 tcy)
阿新 • • 發佈:2018-11-19
typing-型別檢查 2018/11/16
typing-型別檢查
1.1.typing 作用: 型別檢查,防止執行時出現引數和返回值型別不符合。 作為開發文件附加說明,方便使用者呼叫時傳入和返回引數型別。 該模組加入後並不會影響程式的執行,不會報正式的錯誤,只有提醒。 傳入引數: 通過“引數名:型別”的形式宣告引數的型別; 返回結果: 通過"-> 結果型別" 的形式宣告結果的型別。 說明: 呼叫時候引數型別不正確pycharm會有提醒,但不會影響程式的執行。 “-> List[str]”, 規定返回的是列表,並且元素是字串。
typing常用型別:
int, long, float: 整型, 長整形, 浮點型;
bool, str: 布林型,字串型別;
List, Tuple, Dict, Set:列表,元組,字典, 集合;
Iterable, Iterator:可迭代型別,迭代器型別;
Generator:生成器型別;
2.例項1: from typing import List, Tuple, Dict def fun1(a0:int,s0:str,f0:float,b0:bool)->Tuple[List,Tuple,Dict,bool]: list1 = list(range(a0)) tup1 = (a0, s0, f0,b0) dict1 = {s0: f0} b1 = b0 return list1, tup1, dict1, b1 print(fun1(5, "KeyName", 2.3, False)) # ([0, 1, 2, 3, 4], (5, 'KeyName', 2.3, False), {'KeyName': 2.3}, False
例項2:
from typing import List
def func(a: int,b: str) -> List[int or str]:# 使用or關鍵字表示多種型別
list1 = []
list1.append(a)
list1.append(b)
return list1
例項3:
import typing
T=typing.TypeVar('T',int,float,str)
def foo(name:T)->str:
return str(name)
print(foo(2.012))
例項4: NewId=typing.NewType('NewId',int) type(NewId)# <class 'function'> b=NewId(22) type(b)# <class 'int'>