轉(zhuǎn)自: 團(tuán)子的小窩 , 本文固定鏈接: 理解 Python 中的 *args 和 **kwargs
Python是支持可變參數(shù)的傲诵,最簡(jiǎn)單的方法莫過于使用默認(rèn)參數(shù)呆细,例如:
def test_defargs(one, two = 2):
print 'Required argument: ', one
print 'Optional argument: ', two
test_defargs(1)
# result:
# Required argument: 1
# Optional argument: 2
test_defargs(1, 3)
# result:
# Required argument: 1
# Optional argument: 3
當(dāng)然领斥,本文主題并不是講默認(rèn)參數(shù)擦秽,而是另外一種達(dá)到可變參數(shù) (Variable Argument) 的方法:使用*args和**kwargs語(yǔ)法怀骤。其中启绰,*args是可變的positional arguments列表,**kwargs是可變的keyword arguments列表簸淀。并且瓶蝴,*args必須位于**kwargs之前,因?yàn)閜ositional arguments必須位于keyword arguments之前租幕。
首先介紹兩者的基本用法舷手。
下面一個(gè)例子使用*args,同時(shí)包含一個(gè)必須的參數(shù):
def test_args(first, *args):
print 'Required argument: ', first
for v in args:
print 'Optional argument: ', v
test_args(1, 2, 3, 4)
# result:
# Required argument: 1
# Optional argument: 2
# Optional argument: 3
# Optional argument: 4
下面一個(gè)例子使用kwargs, 同時(shí)包含一個(gè)必須的參數(shù)和args列表:
def test_kwargs(first, *args, **kwargs):
print 'Required argument: ', first
for v in args:
print 'Optional argument (*args): ', v
for k, v in kwargs.items():
print 'Optional argument %s (*kwargs): %s' % (k, v)
test_kwargs(1, 2, 3, 4, k1=5, k2=6)
# results:
# Required argument: 1
# Optional argument (*args): 2
# Optional argument (*args): 3
# Optional argument (*args): 4
# Optional argument k2 (*kwargs): 6
# Optional argument k1 (*kwargs): 5
*args和**kwargs語(yǔ)法不僅可以在函數(shù)定義中使用劲绪,同樣可以在函數(shù)調(diào)用的時(shí)候使用男窟。不同的是,如果說在函數(shù)定義的位置使用*args和**kwargs是一個(gè)將參數(shù)pack的過程贾富,那么在函數(shù)調(diào)用的時(shí)候就是一個(gè)將參數(shù)unpack的過程了歉眷。下面使用一個(gè)例子來加深理解:
def test_args(first, second, third, fourth, fifth):
print 'First argument: ', first
print 'Second argument: ', second
print 'Third argument: ', third
print 'Fourth argument: ', fourth
print 'Fifth argument: ', fifth
# Use *args
args = [1, 2, 3, 4, 5]
test_args(*args)
# results:
# First argument: 1
# Second argument: 2
# Third argument: 3
# Fourth argument: 4
# Fifth argument: 5
# Use **kwargs
kwargs = {
'first': 1,
'second': 2,
'third': 3,
'fourth': 4,
'fifth': 5
}
test_args(**kwargs)
# results:
# First argument: 1
# Second argument: 2
# Third argument: 3
# Fourth argument: 4
# Fifth argument: 5
使用*args和**kwargs可以非常方便的定義函數(shù),同時(shí)可以加強(qiáng)擴(kuò)展性颤枪,以便日后的代碼維護(hù)汗捡。