原創文章,歡迎轉載。轉載請註明:轉載自 祥的博客
原文鏈接:https://blog.csdn.net/humanking7/article/details/96600615
Python函數的各種傳參
0. 環境
python3.6
1. 位置參數
沒什麼好說的,和C++語言
都一樣,不過調用起來有點方便,就以冪運算爲例吧。
# x是底數,n爲冪次
def power(x, n):
ret = 1
while n > 0:
n = n - 1
ret = ret * x
return ret
調用函數的時候,一個蘿蔔一個坑,按部就班就ok了
>> power(3,2)
>> 9
2. 默認參數
# x是底數,n爲冪次(默認函數執行平方運算)
def power(x, n=2):
ret = 1
while n > 0:
n = n - 1
ret = ret * x
return ret
>> power(3)
9
>>
這也和C++
中定義函數一樣,可以在聲明中設置默認參數,不過要注意的是:
必須設定參數在前(如函數中的底數
x
),默認參數(如函數中的冪次n
)在後,否則Python
的解釋器會報錯
這樣做的好處是什麼?當然是調用起來省事啦,懶惰纔是第一生產力!
注意:
設定默認參數時,默認值
必須是一個不變的對象,比如說上述例子中n=2
中的2
。
3. 可變參數
3.1. 用法
編寫一個函數sum()
可以計算傳入變量的和。
def sum(*numbers):
ret = 0
print(type(numbers)) # 測試參數類型
for n in numbers:
ret = ret + n
return ret
>> print(sum(1, 2, 3, 4, 5))
<class 'tuple'>
15
>> print(sum())
<class 'tuple'>
0
>>
可以看出,在定義函數時,在參數
前面加入一個*
,就可以使得函數內部得到一個tuple
數組。
3.2. 簡潔調用方法
如果已經有了一個list
或是tuple
,要傳入一個有可變參數的函數,有兩種方法。
- 方法1: 把
list
或是tuple
用下標,一個一個傳入(麻煩) - 方法2: 在傳入參數(
list
或是tuple
)的變量名前加*
(有點類似C語言
指針的用法,自己體會一下吧)
>> ns = [1, 2, 3]
# 方法1(麻煩)
>> sum(ns[0], ns[1], ns[2])
# 方法2(推薦)
>> sum(*ns)
4. 關鍵字參數
4.1. 用法
- 可變參數 允許你傳入
0
個或任意個
參數,這些可變參數在函數調用時自動組裝爲一個tuple
- 關鍵字參數 允許你傳入
0
個或任意個
含 參數名的參數,這些關鍵字參數在函數內部自動組裝爲一個dict
def car(brand, price, **kw):
print("brand: ", brand)
print("price: ", price)
print("kw: ", kw)
print("type(kw): ", type(kw))
# 情況1
>> car('Volkswagen', '9999')
brand: Volkswagen
price: 9999
kw: {}
type(kw): <class 'dict'>
>>
# 情況2
>> car('Volkswagen', '9999', place='Germany', salePlace='China')
brand: Volkswagen
price: 9999
kw: {'place': 'Germany', 'salePlace': 'China'}
type(kw): <class 'dict'>
>>
4.2. 簡潔調用方法
類似3.2節
,如果已經有了一個字典dict
,可以在調用函數時把它當做關鍵字參數
傳入進入,只需要在前面變量名前加**
>> extraParam = {'place': 'Germany', 'salePlace': 'China'}
>> car('Volkswagen', '9999', **extraParam)
brand: Volkswagen
price: 9999
kw: {'place': 'Germany', 'salePlace': 'China'}
type(kw): <class 'dict'>
>>
4.3. 檢查關鍵字參數
其實就是檢查字典dict
def car(brand, price, **kw):
print("brand: ", brand)
print("price: ", price)
print("kw: ", kw)
print("type(kw): ", type(kw))
# 檢查代碼
if 'place' in kw:
# 有place這個參數
pass
if 'salePlace' in kw:
# 有salePlace這個參數
pass
5. 命名關鍵字參數
5.1. 用法
如果要 限制 關鍵字參數 的 名字
,就可以用 命名關鍵字參數,例如,只接收place
和salePlace
作爲 關鍵字參數。這種方式定義的函數如下所示:
def car2(brand, price, *, place, salePlace):
print("brand: ", brand)
print("price: ", price)
print("place: ", place)
print("salePlace: ", salePlace)
print("type(place): ", type(place))
print("type(salePlace): ", type(salePlace))
和關鍵字參數**kw
不同,命名關鍵字參數需要一個特殊分隔符*
,*
後面的參數被視爲命名關鍵字參數。
運行情況:
# 情況1
>> car2('Volkswagen', '9999', place='Germany', salePlace='China')
brand: Volkswagen
price: 9999
place: Germany
salePlace: China
type(place): <class 'str'>
type(salePlace): <class 'str'>
# 情況2
>> car2('Volkswagen', '9999', 'Germany', 'China')
Traceback (most recent call last):
car2('Volkswagen', '9999', 'Germany', 'China')
TypeError: car2() takes 2 positional arguments but 4 were given
# 情況3
>> car2('Volkswagen', '9999', salePlace='China')
Traceback (most recent call last):
car2('Volkswagen', '9999', salePlace='China')
TypeError: car2() missing 1 required keyword-only argument: 'place'
# 情況4
>> car2('Volkswagen', '9999', place='Germany', salePlace='China', city = 'beijing')
Traceback (most recent call last):
car2('Volkswagen', '9999', place='Germany', salePlace='China', city = 'beijing')
TypeError: car2() got an unexpected keyword argument 'city'
解釋:
- 情況1: 一般調用方式;
- 情況2: 因爲調用時缺少參數名
place
和salePlace
,Python解釋器把這4
個參數均視爲位置參數
,但car2()函數
僅接受2
個位置參數
; - 情況3: 由於沒有設置默認值,所以命名關鍵字參數不可以省略;
- 情況4: 沒有定義
city
這個命名關鍵字參數。
注意:
命名關鍵字參數必須傳入參數名,這和位置參數不同。如果沒有傳入參數名,調用將報錯,如情況2所示。
針對情況3出現的問題,只需要設置好參數的默認值就可以避免了:
def car2(brand, price, *, place='', salePlace=''):
print("brand: ", brand)
print("price: ", price)
print("place: ", place)
print("salePlace: ", salePlace)
print("type(place): ", type(place))
print("type(salePlace): ", type(salePlace))
# 情況1
>> car2('Volkswagen', '9999')
brand: Volkswagen
price: 9999
place:
salePlace:
type(place): <class 'str'>
type(salePlace): <class 'str'>
# 情況2
>> car2('Volkswagen', '9999', salePlace='China')
brand: Volkswagen
price: 9999
place:
salePlace: China
type(place): <class 'str'>
type(salePlace): <class 'str'>
5.2… 特殊情況
如果函數定義中已經有了一個可變參數,後面跟着的命名關鍵字參數就不再需要一個特殊分隔符*
了:
def car3(brand, price, *args, place='', salePlace=''):
print("brand: ", brand)
print("price: ", price)
print("args: ", args)
print("place: ", place)
print("salePlace: ", salePlace)
print("type(args): ", type(args))
print("type(place): ", type(place))
print("type(salePlace): ", type(salePlace))
運行情況:
# 將place參數省略,使用默認參數
>> car3('Volkswagen', '9999', 1, 2, 3, salePlace='China')
brand: Volkswagen
price: 9999
args: (1, 2, 3)
place:
salePlace: China
type(args): <class 'tuple'>
type(place): <class 'str'>
type(salePlace): <class 'str'>
注意:
使用命名關鍵字參數時,如果沒有可變參數,就必須加一個*
作爲特殊分隔符。如果缺少*
,Python解釋器將其視爲位置參數
6. 組合參數
在Python中定義函數,可以用必選參數、默認參數、可變參數、關鍵字參數和命名關鍵字參數,這5種參數都可以組合使用。
注意:
參數定義的順序必須是:必選參數、默認參數、可變參數、命名關鍵字參數、關鍵字參數。
我的建議是:別亂搞,函數接口理解性變差,損人不利己。
7. 參考文獻
廖雪峯Python教程:https://www.liaoxuefeng.com/wiki/1016959663602400/1017261630425888
OK!
以上,Enjoy~
i