Python 函數(shù)參數(shù)與解包 - PyTips 0x05

PyTips

項目地址:https://git.io/pytips

函數(shù)調(diào)用的參數(shù)規(guī)則與解包

Python 的函數(shù)在聲明參數(shù)時大概有下面 4 種形式:

  1. 不帶默認值的:def func(a): pass
  2. 帶有默認值的:def func(a, b = 1): pass
  3. 任意位置參數(shù):def func(a, b = 1, *c): pass
  4. 任意鍵值參數(shù):def func(a, b = 1, *c, **d): pass

在調(diào)用函數(shù)時,有兩種情況:

  1. 沒有關(guān)鍵詞的參數(shù):func("G", 20)
  2. 帶有關(guān)鍵詞的參數(shù):func(a = "G", b = 20)(其中帶有關(guān)鍵詞調(diào)用可以不考慮順序:func(b = 20, a = "G"

當然,這兩種情況是可以混用的:func("G", b = 20),但最重要的一條規(guī)則是位置參數(shù)不能在關(guān)鍵詞參數(shù)之后出現(xiàn)

def func(a, b = 1):
    pass
func(a = "G", 20) # SyntaxError 語法錯誤
  File "<ipython-input-1-3ca775953480>", line 3
    func(a = "G", 20) # SyntaxError 語法錯誤
                 ^
SyntaxError: positional argument follows keyword argument

另外一條規(guī)則是:位置參數(shù)優(yōu)先權(quán)

def func(a, b = 1):
    pass
func(20, a = "G") # TypeError 對參數(shù) a 重復賦值
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-2-cbaa9a1fe24d> in <module>()
      1 def func(a, b = 1):
      2     pass
----> 3 func(20, a = "G") # TypeError 對參數(shù) a 重復賦值


TypeError: func() got multiple values for argument 'a'

最保險的方法就是全部采用關(guān)鍵詞參數(shù)。

任意參數(shù)

任意參數(shù)可以接受任意數(shù)量的參數(shù),其中*a的形式代表任意數(shù)量的位置參數(shù),**d代表任意數(shù)量的關(guān)鍵詞參數(shù):

def concat(*lst, sep = "/"):
    return sep.join((str(i) for i in lst))

print(concat("G", 20, "@", "Hz", sep = ""))
G20@Hz

上面的這個def concat(*lst, sep = "/")的語法是PEP 3102提出的,在 Python 3.0 之后實現(xiàn)。這里的關(guān)鍵詞函數(shù)必須明確指明,不能通過位置推斷:

print(concat("G", 20, "-")) # Not G-20
G/20/-

**d則代表任意數(shù)量的關(guān)鍵詞參數(shù)

def dconcat(sep = ":", **dic):
    for k in dic.keys():
        print("{}{}{}".format(k, sep, dic[k]))

dconcat(hello = "world", python = "rocks", sep = "~")
hello~world
python~rocks

Unpacking

Python 3.5 添加的新特性(PEP 448),使得*a**d可以在函數(shù)參數(shù)之外使用:

print(*range(5))
lst = [0, 1, 2, 3]
print(*lst)

a = *range(3), # 這里的逗號不能漏掉
print(a)

d = {"hello": "world", "python": "rocks"}
print({**d}["python"])
0 1 2 3 4
0 1 2 3
(0, 1, 2)
rocks

所謂的解包(Unpacking)實際上可以看做是去掉()的元組或者是去掉{}的字典。這一語法也提供了一個更加 Pythonic 地合并字典的方法:

user = {'name': "Trey", 'website': "http://treyhunner.com"}
defaults = {'name': "Anonymous User", 'page_name': "Profile Page"}

print({**defaults, **user})
{'page_name': 'Profile Page', 'name': 'Trey', 'website': 'http://treyhunner.com'}

在函數(shù)調(diào)用的時候使用這種解包的方法則是 Python 2.7 也可以使用的:

print(concat(*"ILovePython"))
I/L/o/v/e/P/y/t/h/o/n

參考

  1. The Idiomatic Way to Merge Dictionaries in Python
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容