Python学习札记(十三) Function3 函数参数二
參考:函數(shù)參數(shù)
Note
A.關(guān)鍵字參數(shù):
1.關(guān)鍵字參數(shù):**kw
可變參數(shù)允許你傳入0個或任意個參數(shù),這些可變參數(shù)在函數(shù)調(diào)用時自動組裝為一個tuple。而關(guān)鍵字參數(shù)允許你傳入0個或任意個含參數(shù)名的參數(shù),這些關(guān)鍵字參數(shù)在函數(shù)內(nèi)部自動組裝為一個dict。
2.支持只傳入必選參數(shù);也可以傳入任意數(shù)目的可選參數(shù),如下例。
eg.
#!/usr/bin/env python3def my_func(name, age, **kw) :print('name:', name, 'age:', age, 'else:', kw)test
>>> from function3 import my_func>>> my_func('Chen', 20) name: Chen age: 20 else: {}>>> my_func('Chen', 20, prof='Student') name: Chen age: 20 else: {'prof': 'Student'}>>> my_func('Chen', 20, prof='Student', city='FuZhou') name: Chen age: 20 else: {'prof': 'Student', 'city': 'FuZhou'}3.關(guān)鍵字參數(shù)的作用:”試想你正在做一個用戶注冊的功能,除了用戶名和年齡是必填項外,其他都是可選項,利用關(guān)鍵字參數(shù)來定義這個函數(shù)就能滿足注冊的需求。“
4.當然,也可以選擇在傳入?yún)?shù)的時候直接傳入一個dict的內(nèi)容。這里容易出錯,我就翻車了。
eg.
>>> dic = {'prof' : 'Student', 'city' : 'FuZhou'} >>> my_func('Chen', 20, dic['prof'], dic['city']) Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: my_func() takes 2 positional arguments but 4 were given>>> my_func('Chen', 20, dic) Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: my_func() takes 2 positional arguments but 3 were given第一句錯誤的原因,是因為傳入dic['prof']相當于傳入'Student',即一個字符串,這很明顯與函數(shù)定義的參數(shù)不符;第二句同上,只不過由傳入字符串變成了傳入一個dict。
正確的方法應該是value_name=dict[key]。
eg.
>>> my_func('Chen', 20, prof=dic['prof']) name: Chen age: 20 else: {'prof': 'Student'}>>> my_func('Chen', 20, prof=dic['prof'], city=dic['city']) name: Chen age: 20 else: {'prof': 'Student', 'city': 'FuZhou'}5.如果想直接傳入dict,方法也很簡單,加上兩個星號*:
剛才的錯誤:
>>> my_func('Chen', 20, dic) Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: my_func() takes 2 positional arguments but 3 were given修正:
>>> my_func('Chen', 20, **dic) name: Chen age: 20 else: {'prof': 'Student', 'city': 'FuZhou'}**dic表示把dic這個dict的所有key-value用關(guān)鍵字參數(shù)傳入到函數(shù)的**kw參數(shù),kw將獲得一個dict,注意kw獲得的dict是dic的一份拷貝,對kw的改動不會影響到函數(shù)外的dic。
B.命名關(guān)鍵字參數(shù)
1.定義了關(guān)鍵字參數(shù)的函數(shù)允許用戶傳入多個關(guān)鍵字key-value值,如果我們想要在函數(shù)里面查看一個key是否在傳入的dict中,可以通過if···in···的方法查看。
eg.
#!/usr/bin/env python3def my_func(name, age, **kw) :if 'prof' in kw : # Hint: 'prof' => ''print('prof in')if 'city' in kw :print('city in')print('name:', name, 'age:', age, 'else:', kw)output
>>> from function3 import my_func >>> dic = {'prof' : 'Student', 'city' : 'FuZhou'} >>> my_func('Chen', 20, **dic) prof in city in name: Chen age: 20 else: {'city': 'FuZhou', 'prof': 'Student'} >>>2.如果要限制關(guān)鍵字參數(shù)的名字,就可以用命名關(guān)鍵字參數(shù),例如,只接收city和prof作為關(guān)鍵字參數(shù)。
方法:
my_func(name, age, *, prof, city)用*作為分隔符,指定傳入的關(guān)鍵字參數(shù)key必須是prof和city。
使用命名關(guān)鍵字參數(shù)時,要特別注意,如果沒有可變參數(shù),就必須加一個*作為特殊分隔符。如果缺少*,Python解釋器將無法識別位置參數(shù)和命名關(guān)鍵字參數(shù)。
eg.
def my_func2(name, age, *, prof, city) :print(name, age, prof, city)output
>>> from function3 import my_func2 >>> my_func2('Chen', 20, prof='Student', city='FuZhou') Chen 20 Student FuZhou注意:指定了關(guān)鍵字參數(shù)的key之后,傳入的關(guān)鍵字參數(shù)數(shù)目必須匹配,并且必須是 key=value 的形式。
命名關(guān)鍵字參數(shù)必須傳入?yún)?shù)名。
eg.
>>> my_func2('Chen', 20, prof='Student') Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: my_func2() missing 1 required keyword-only argument: 'city'>>> my_func2('Chen', 20) Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: my_func2() missing 2 required keyword-only arguments: 'prof' and 'city' >>> my_func2('Chen', 20, 'Student', 'FuZhou') Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: my_func2() takes 2 positional arguments but 4 were given3.命名關(guān)鍵字支持默認參數(shù),在調(diào)用時,可以不傳入默認參數(shù)的值。
C.參數(shù)組合
在Python中定義函數(shù),可以用必選參數(shù)、默認參數(shù)、可變參數(shù)、關(guān)鍵字參數(shù)和命名關(guān)鍵字參數(shù),這5種參數(shù)都可以組合使用。但是請注意,參數(shù)定義的順序必須是:必選參數(shù)、默認參數(shù)、可變參數(shù)(*[···] or *list_name)、命名關(guān)鍵字參數(shù)和關(guān)鍵字參數(shù)(**{···} or **dict_name)。
eg.
def my_func3(a, b, c=0, *d, **e) :print(a, b, c, d, e)output
>>> my_func3('Chen', 20) Chen 20 0 () {}>>> my_func3('Chen', 20, 100) Chen 20 100 () {}>>> my_func3('Chen', 20, 100, *['Li', 'Wang'], **{'Li' : 'num1', 'Wang' : 'num2'}) Chen 20 100 ('Li', 'Wang') {'Wang': 'num2', 'Li': 'num1'}>>>在函數(shù)調(diào)用的時候,Python解釋器自動按照參數(shù)位置和參數(shù)名把對應的參數(shù)傳進去。
也就出現(xiàn)了原文傳入一個tuple和一個dict,解釋器也正常輸出的情況:
>>> t1 = ('Li', 100, 99, 'Wang')>>> d1 = {'Wang' : 'num2', 'Li' : 'num1'}>>> my_func3(*t1, **d1) Li 100 99 ('Wang',) {'Wang': 'num2', 'Li': 'num1'}>>> t2 = ('Li', 100, 'Wang')>>> my_func3(*t2, **d1) Li 100 Wang () {'Wang': 'num2', 'Li': 'num1'} # 按位置解釋>>> t3 = ['Li', 100, 'Wang']>>> my_func3(*t3, **d1) Li 100 Wang () {'Wang': 'num2', 'Li': 'num1'} # 傳入一個list和一個tuple也可以>>>2017/1/31
轉(zhuǎn)載于:https://www.cnblogs.com/qq952693358/p/6359044.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的Python学习札记(十三) Function3 函数参数二的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2017全国省市区县 json数据
- 下一篇: PythonR语言-python和r相遇