python3 限定使用 keyword 關鍵字的方式作為參數
這篇是從 《Effective Python》: tips 21 學習到的觀念
在我們實作 function 的時候,定義 function specification。為了讓 function 的行為能夠更明確化,我們傾向在傳遞某些參數的時候 "強制" "限定" 使用 keyword方式的寫法來傳遞參數也就是指名 parameter=value 的方式。
這在 Python 裡面稱為 "Keyword-only Arguments"
相較於 Python2, Python3 有特殊的語法來支持這樣的使用方式:
在 parameter list 可以看到 "*" 它是用來標記 positional arguments 的結尾。在這之後的參數都一定要使用 keyword-only 的寫法。
如果這時候,我們使用 3個以上的 positional arguments 的話,會引發 "TypeError"
在我們實作 function 的時候,定義 function specification。為了讓 function 的行為能夠更明確化,我們傾向在傳遞某些參數的時候 "強制" "限定" 使用 keyword方式的寫法來傳遞參數也就是指名 parameter=value 的方式。
這在 Python 裡面稱為 "Keyword-only Arguments"
相較於 Python2, Python3 有特殊的語法來支持這樣的使用方式:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def function(arg1, arg2, *, keyword=False, keyword2=True): | |
... processing ... |
如果這時候,我們使用 3個以上的 positional arguments 的話,會引發 "TypeError"
那 Python2 呢?使用 **kwargs 的方式,並且要手動引發 TypeError 。
留言
張貼留言