欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python中的參數(shù)類型匹配提醒

 更新時(shí)間:2022年12月17日 15:05:48   作者:會(huì)發(fā)paper的學(xué)渣  
這篇文章主要介紹了python中的參數(shù)類型匹配提醒,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

python參數(shù)類型匹配提醒

1、對于常見類型,如下:

def a(b:str):pass

2、List 類型限制:

from typing import List
def a(b:List[str]):pass

3、Dict類型限制:

from typing import Dict
def a(b:Dict[str]):pass
?
def c(b:Dict[str,int]):pass

4、Tuple類型:

from typing import Tuple
def a(b:Tuple[str,int]):pass

5、多類型限制:

from typing import Union
def a(b:Union[str,int,None]):pass

不足:

1、雖然我們指定了List[int]即由int組成的列表,但是,實(shí)際中,只要這個(gè)列表中存在int(其他的可以為任何類型),就不會(huì)出現(xiàn)警告

2、由于python是即是編譯語言,所以pycharm只是提出了警告,但實(shí)際上運(yùn)行時(shí)不一定會(huì)報(bào)錯(cuò),畢竟python的本質(zhì)還是動(dòng)態(tài)語言

Python函數(shù)參數(shù)匹配筆記

位置匹配

def func(a, b, c):
? ? print(a, b, c)

func(1, 2, 3)

輸出:
1 2 3

關(guān)鍵字匹配

def func(a, b, c):
? ? print(a, b, c)

func(c=1, b=2, a=3)

輸出:
3 2 1

默認(rèn)值

def func(a, b=2, c=3):
? ? print(a, b, c)

func(1)

輸出:
1 2 3

傳遞任意數(shù)量參數(shù)

def avg(*scores):
? ? result = sum(scores) / len(scores)
? ? print(result)

avg(60, 70, 80, 90)

輸出:
75.0

若函數(shù)參數(shù)個(gè)數(shù)不確定,定義函數(shù)時(shí)可以采取“*args”的格式,表明傳遞的參數(shù)是元組格式

傳遞的參數(shù)是元組

def avg(*scores):
? ? result = sum(scores) / len(scores)
? ? print(result)

scores = (60, 70, 80, 90)
avg(*scores)

輸出:
75.0

不能直接傳遞元組變量,使用函數(shù)時(shí)傳遞元組要加星號(hào)*解包

傳遞任意數(shù)量鍵值對參數(shù)

def display(**employee):
? ? print(employee)

display(name='Tom', age=22, job='ev')

輸出:
{'name': 'Tom', 'age': 22, 'job': 'ev'}

定義函數(shù)時(shí)使用兩個(gè)星號(hào)**表明傳遞的參數(shù)為字典表的鍵值對格式,使用函數(shù)時(shí)傳遞的參數(shù)寫成字典表的鍵值對形式

傳遞的參數(shù)是字典表

def display(**employee):
? ? print(employee)

emp = {'name': 'Tom', 'age': 22, 'job': 'dev'}
display(**emp)

輸出:
{'name': 'Tom', 'age': 22, 'job': 'ev'}

直接傳遞字典表要加兩個(gè)星號(hào)**解包

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論