Python函數(shù)參數(shù)和注解的使用
四種參數(shù)
Python函數(shù)func定義如下:
def func(first, *args, second="Hello World", **kwargs):
print(first)
print(args)
print(second)
print(kwargs)
func("dongfanger", "san", py="good")
運(yùn)行后會(huì)輸出:
dongfanger
('san',)
Hello World
{'py': 'good'}
它有四種參數(shù):
- first是定位參數(shù),positional parameter,不可省略。
- *args是可變參數(shù),arguments,存入元組。
- second是默認(rèn)值參數(shù),default argument values,可以省略。
- **args是關(guān)鍵字參數(shù),keyword arguments,存入字典。
func函數(shù)的調(diào)用方式有以下這些:
①傳入單個(gè)定位參數(shù)。
func("dongfanger")
dongfanger
()
Hello World
{}
②第一個(gè)參數(shù)后的任意個(gè)參數(shù)會(huì)被*args捕獲,存入一個(gè)元組。
func("dongfanger", "a", "b", "c")
dongfanger
('a', 'b', 'c')
Hello World
{}
③沒有明確指定名稱的關(guān)鍵字參數(shù)會(huì)被**kwargs捕獲,存入一個(gè)字典。
func("dongfanger", j="1", k="2")
dongfanger
()
Hello World
{'j': '1', 'k': '2'}
④second只能作為關(guān)鍵字參數(shù)傳入。
func("dongfanger", second="cool")
dongfanger
()
cool
{}
⑤定位函數(shù)也能作為關(guān)鍵字參數(shù)傳入。
func(first="san")
san
()
Hello World
{}
⑥字典前加上**,其所有元素作為單個(gè)參數(shù)傳入,同名鍵會(huì)綁定到對(duì)應(yīng)具名參數(shù)上,余下的被**args捕獲。
my_dict = {"first": "dongfanger", "location": "cd", "second": "cool", "age": "secret"}
func(**my_dict)
dongfanger
()
cool
{'location': 'cd', 'age': 'secret'}
除了這四種參數(shù),還有一種Python3新增加的僅限關(guān)鍵字參數(shù)。
僅限關(guān)鍵字參數(shù)
僅限關(guān)鍵字參數(shù)(keyword-only argument)是Python3的新特性,func函數(shù)的second參數(shù)就是僅限關(guān)鍵字參數(shù),“僅限”的意思是說,只能通過關(guān)鍵字參數(shù)指定,它一定不會(huì)捕獲未命名的定位參數(shù)。
假如把參數(shù)位置調(diào)整一下定義another_func函數(shù):
def another_func(first, another_second="Hello World", *args, **kwargs):
print(first)
print(another_second)
print(args)
print(kwargs)
another_func("dongfanger", "a", "b", "c")
輸出會(huì)變成:
dongfanger
a # 注意這里
('b', 'c')
{}
another_second不是僅限關(guān)鍵字參數(shù),而只是默認(rèn)值參數(shù),因?yàn)樗东@到了定位參數(shù)。
由此得知,定義僅限關(guān)鍵字參數(shù),必須把它放到*args參數(shù)后面,就像func函數(shù)一樣,反例是another_func函數(shù)。
還有第二個(gè)方法定義僅限關(guān)鍵字參數(shù),在簽名中放一個(gè)*:
>>> def f(a, *, b): # b是僅限關(guān)鍵字參數(shù) ... return a, b ... >>> f(1, b=2) # 只能傳關(guān)鍵字參數(shù) (1, 2) >>> f(1, 2) # 不能傳定位參數(shù) Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: f() takes 1 positional argument but 2 were given >>> f(1, 2, 3) # 不能傳定位參數(shù) Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: f() takes 1 positional argument but 3 were given
僅限關(guān)鍵字參數(shù)不一定要有默認(rèn)值,就像b一樣,強(qiáng)制必須傳入實(shí)參。
內(nèi)省中的函數(shù)參數(shù)
函數(shù)內(nèi)省的意思是說,當(dāng)你拿到一個(gè)“函數(shù)對(duì)象”的時(shí)候,你可以繼續(xù)知道,它的名字,參數(shù)定義等信息。這些信息可以通過函數(shù)對(duì)象的屬性(一些雙下劃線的魔法方法)得到。
對(duì)于func函數(shù):
def func(first, *args, second="Hello World", **kwargs):
print(first)
print(second)
print(args)
print(kwargs)
和another_func函數(shù):
def another_func(first, another_second="Hello World", *args, **kwargs):
print(first)
print(another_second)
print(args)
print(kwargs)
【__defaults__屬性】
元組,保存著定位參數(shù)和關(guān)鍵字參數(shù)的默認(rèn)值。
print(func.__defaults__) # None
print(another_func.__defaults__) # ('Hello World',)
【__kwdefaults__屬性】
字典,保存僅限關(guān)鍵字參數(shù)。
print(func.__kwdefaults__) # {'second': 'Hello World'}
print(another_func.__kwdefaults__) # None
【__code__屬性】
code對(duì)象引用,code對(duì)象自身有很多屬性,其中包括參數(shù)名稱。
print(func.__code__.co_varnames) # ('first', 'second', 'args', 'kwargs')
print(another_func.__code__.co_varnames) # ('first', 'another_second', 'args', 'kwargs')
另外還可以使用inspect庫的signature方法來查看內(nèi)省中的函數(shù)參數(shù):
from inspect import signature print(signature(func)) # (first, *args, second='Hello World', **kwargs)
框架和IDE等工具可以使用這些信息驗(yàn)證代碼。
函數(shù)注解
如果刷過力扣算法題,那么對(duì)函數(shù)注解就不會(huì)陌生。比如:
def clip(text:str, max_len:'int > 0'=80) -> str:
pass
參數(shù):后面是注解表達(dá)式,可以用來注解參數(shù)類型和約束。如果參數(shù)有默認(rèn)值,注解放在參數(shù)名和=號(hào)之間。
可以在函數(shù)末尾的)和:之間添加->和注解表達(dá)式,來對(duì)返回值添加注解。
注解表達(dá)式可以是任何類型,最常用的類型是類(如str或int)和字符串(如'int > 0')。
函數(shù)注解只是個(gè)注解,Python對(duì)注解所做的唯一的事情是,把它們存入函數(shù)的__annotations__屬性中:
print(clip.__annotations__)
#{'text': <class 'str'>, 'max_len': 'int > 0', 'return': <class 'str'>}
Python不做檢查,不做強(qiáng)制,不做驗(yàn)證,什么操作都不做!注解只是元數(shù)據(jù),可以供框架和IDE等工具使用。
以上就是Python函數(shù)參數(shù)和注解的使用的詳細(xì)內(nèi)容,更多關(guān)于Python函數(shù)參數(shù)和注解的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python 中文件輸入輸出及os模塊對(duì)文件系統(tǒng)的操作方法
這篇文章主要介紹了python 中文件輸入輸出及os模塊對(duì)文件系統(tǒng)的操作方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-08-08
python3實(shí)現(xiàn)釘釘消息推送的方法示例
這篇文章主要介紹了python3實(shí)現(xiàn)釘釘消息推送的方法示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
python selenium自動(dòng)化測試框架搭建的方法步驟
這篇文章主要介紹了python selenium自動(dòng)化測試框架搭建的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
使用matplotlib修改坐標(biāo)軸,將y軸的間距設(shè)置為某一個(gè)值
這篇文章主要介紹了使用matplotlib修改坐標(biāo)軸,將y軸的間距設(shè)置為某一個(gè)值方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
利用 Flask 動(dòng)態(tài)展示 Pyecharts 圖表數(shù)據(jù)方法小結(jié)
本文將介紹如何在 web 框架 Flask 中使用可視化工具 pyecharts, 看完本教程你將掌握幾種動(dòng)態(tài)展示可視化數(shù)據(jù)的方法。感興趣的朋友跟隨小編一起看看吧2019-09-09
Python字符串對(duì)齊、刪除字符串不需要的內(nèi)容以及格式化打印字符
這篇文章主要給大家介紹了關(guān)于Python字符串對(duì)齊、刪除字符串不需要的內(nèi)容以及格式化打印字符的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Python語言實(shí)現(xiàn)百度語音識(shí)別API的使用實(shí)例
這篇文章主要介紹了Python語言實(shí)現(xiàn)百度語音識(shí)別API的使用實(shí)例,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12
Python 多模式字符串搜索 Aho-Corasick詳解
Aho-Corasick 算法是一種用于精確或近似多模式字符串搜索的高效算法,本文給大家介紹Python 多模式字符串搜索 Aho-Corasick的相關(guān)知識(shí),感興趣的朋友跟隨小編一起看看吧2025-01-01

