Python函數參數和注解是什么


四種參數

Python函數func定義如下:

def func(first, *args, second="Hello World", **kwargs):
    print(first)
    print(args)
    print(second)
    print(kwargs)


func("dongfanger", "san", py="good")

運行后會輸出:

dongfanger
('san',)
Hello World
{'py': 'good'}

它有四種參數:

  • first是定位參數,positional parameter,不可省略。
  • *args是可變參數,arguments,存入元組。
  • second是默認值參數,default argument values,可以省略。
  • **args是關鍵字參數,keyword arguments,存入字典。

func函數的調用方式有以下這些:

①傳入單個定位參數。

func("dongfanger")  
dongfanger
()
Hello World
{}

②第一個參數后的任意個參數會被*args捕獲,存入一個元組。

func("dongfanger", "a", "b", "c")
dongfanger
('a', 'b', 'c')
Hello World
{}

③沒有明確指定名稱的關鍵字參數會被**kwargs捕獲,存入一個字典。

func("dongfanger", j="1", k="2")
dongfanger
()
Hello World
{'j': '1', 'k': '2'}

④second只能作為關鍵字參數傳入。

func("dongfanger", second="cool")
dongfanger
()
cool
{}

⑤定位函數也能作為關鍵字參數傳入。

func(first="san")
san
()
Hello World
{}

⑥字典前加上**,其所有元素作為單個參數傳入,同名鍵會綁定到對應具名參數上,余下的被**args捕獲。

my_dict = {"first": "dongfanger", "location": "cd", "second": "cool", "age": "secret"}
func(**my_dict)
dongfanger
()
cool
{'location': 'cd', 'age': 'secret'}

除了這四種參數,還有一種Python3新增加的僅限關鍵字參數。

僅限關鍵字參數

僅限關鍵字參數(keyword-only argument)是Python3的新特性,func函數的second參數就是僅限關鍵字參數,“僅限”的意思是說,只能通過關鍵字參數指定,它一定不會捕獲未命名的定位參數。

假如把參數位置調整一下定義another_func函數:

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

輸出會變成:

dongfanger
a  # 注意這里
('b', 'c')
{}

another_second不是僅限關鍵字參數,而只是默認值參數,因為它捕獲到了定位參數。

由此得知,定義僅限關鍵字參數,必須把它放到*args參數后面,就像func函數一樣,反例是another_func函數。

還有第二個方法定義僅限關鍵字參數,在簽名中放一個*

>>> def f(a, *, b):  # b是僅限關鍵字參數
...    return a, b
...
>>> f(1, b=2)  # 只能傳關鍵字參數
(1, 2)
>>> f(1, 2)  # 不能傳定位參數
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)  # 不能傳定位參數
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: f() takes 1 positional argument but 3 were given

僅限關鍵字參數不一定要有默認值,就像b一樣,強制必須傳入實參。

內省中的函數參數

函數內省的意思是說,當你拿到一個“函數對象”的時候,你可以繼續知道,它的名字,參數定義等信息。這些信息可以通過函數對象的屬性(一些雙下划線的魔法方法)得到。

對於func函數:

def func(first, *args, second="Hello World", **kwargs):
    print(first)
    print(second)
    print(args)
    print(kwargs)

和another_func函數:

def another_func(first, another_second="Hello World", *args,  **kwargs):
    print(first)
    print(another_second)
    print(args)
    print(kwargs)

__defaults__屬性】

元組,保存着定位參數和關鍵字參數的默認值。

print(func.__defaults__)  # None

print(another_func.__defaults__)  # ('Hello World',)

__kwdefaults__屬性】

字典,保存僅限關鍵字參數。

print(func.__kwdefaults__)  # {'second': 'Hello World'}

print(another_func.__kwdefaults__)  # None

__code__屬性】

code對象引用,code對象自身有很多屬性,其中包括參數名稱。

print(func.__code__.co_varnames)  # ('first', 'second', 'args', 'kwargs')

print(another_func.__code__.co_varnames)  # ('first', 'another_second', 'args', 'kwargs')

另外還可以使用inspect庫的signature方法來查看內省中的函數參數:

from inspect import signature

print(signature(func))  
# (first, *args, second='Hello World', **kwargs)

框架和IDE等工具可以使用這些信息驗證代碼。

函數注解

如果刷過力扣算法題,那么對函數注解就不會陌生。比如:

def clip(text:str, max_len:'int > 0'=80) -> str:
    pass

參數:后面是注解表達式,可以用來注解參數類型和約束。如果參數有默認值,注解放在參數名和=號之間。

可以在函數末尾的):之間添加->和注解表達式,來對返回值添加注解。

注解表達式可以是任何類型,最常用的類型是類(如str或int)和字符串(如'int > 0')。

函數注解只是個注解,Python對注解所做的唯一的事情是,把它們存入函數的__annotations__屬性中:

print(clip.__annotations__)
#{'text': <class 'str'>, 'max_len': 'int > 0', 'return': <class 'str'>}

Python不做檢查,不做強制,不做驗證,什么操作都不做!注解只是元數據,可以供框架和IDE等工具使用。

小結

本文介紹了Python函數的四種參數:定位參數、可變參數、默認值參數、關鍵字參數,和第五種Python3新特性參數:僅限關鍵字參數。拿到一個函數對象后,可以通過函數屬性(一些雙下划線的魔法方法)查看內省中的參數信息。函數注解是一種元數據,存在__annotations__屬性中,備注函數的參數和返回值的類型,它只是個注解,Python不會做任何強制檢查

參考資料:

《流暢的Python》

https://blog.csdn.net/cadi2011/article/details/86641811

https://segmentfault.com/q/1010000012595419

更文進度

由於個人原因,寫文章時間變少了,雖然我仍然會努力碼字,但是更文頻率不得不降低。

從本周起公眾號改周更了!固定周五早上七點半推送!細水流長不負讀者期望!

時間跨度加長可能會導致內容連續性變弱,影視劇做法是設置上集回顧和下集預告,我借鑒了這個做法,在公眾號文章最后附加了“更文進度“,告知以前更新了什么,以后會更新什么。

【上文回顧】

歸檔電子書:

https://dongfanger.gitee.io/blog/

【下文預告】

順序不分先后,只列舉我想到的可能會更新的內容:

  • Python進階系列,二刷流暢的Python函數相關章節
  • teprunner測試平台,測試計划增刪改查
  • teprunner測試平台,前端適配小屏電腦優化改造
  • teprunner測試平台,定時任務
  • teprunner測試平台,Dashboard
  • teprunner測試平台,小工具共享腳本


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM