5 回答

TA貢獻1898條經(jīng)驗 獲得超8個贊
的*args
和**kwargs
是一種常見的成語,以允許參數(shù),以作為部分所述功能的任意數(shù)量的多個上定義函數(shù) Python文檔英寸
該*args
給你的所有函數(shù)參數(shù)為一個元組:
In [1]: def foo(*args): ...: for a in args: ...: print a ...: ...: In [2]: foo(1)1In [4]: foo(1,2,3)123
該**kwargs
會給你所有的 關(guān)鍵字參數(shù)除了那些與作為字典的形式參數(shù)。
In [5]: def bar(**kwargs): ...: for a in kwargs: ...: print a, kwargs[a] ...: ...: In [6]: bar(name='one', age=27)age 27name one
這兩個習語可以與普通參數(shù)混合使用,以允許一組固定和一些變量參數(shù):
def foo(kind, *args, **kwargs): pass
*l
習慣用法的另一個用法是在調(diào)用函數(shù)時解包參數(shù)列表。
In [9]: def foo(bar, lee): ...: print bar, lee ...: ...: In [10]: l = [1,2]In [11]: foo(*l)1 2
在Python 3中,可以*l
在賦值的左側(cè)使用(Extended Iterable Unpacking),盡管在此上下文中它給出了一個列表而不是一個元組:
first, *rest = [1,2,3,4]first, *l, last = [1,2,3,4]
Python 3也增加了新的語義(參考PEP 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2): pass
這樣的函數(shù)只接受3個位置參數(shù),后面的所有內(nèi)容*
只能作為關(guān)鍵字參數(shù)傳遞。

TA貢獻2012條經(jīng)驗 獲得超12個贊
值得注意的是,您也可以使用*和**調(diào)用函數(shù)。這是一個快捷方式,允許您使用列表/元組或字典直接將多個參數(shù)傳遞給函數(shù)。例如,如果您具有以下功能:
def foo(x,y,z):
print("x=" + str(x))
print("y=" + str(y))
print("z=" + str(z))
你可以這樣做:
>>> mylist = [1,2,3]
>>> foo(*mylist)
x=1
y=2
z=3
>>> mydict = {'x':1,'y':2,'z':3}
>>> foo(**mydict)
x=1
y=2
z=3
>>> mytuple = (1, 2, 3)
>>> foo(*mytuple)
x=1
y=2
z=3
注意:鍵的名稱mydict必須與函數(shù)的參數(shù)完全相同foo。否則會拋出TypeError:
>>> mydict = {'x':1,'y':2,'z':3,'badnews':9}
>>> foo(**mydict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'badnews'

TA貢獻1820條經(jīng)驗 獲得超2個贊
單*表示可以有任意數(shù)量的額外位置參數(shù)。foo()可以調(diào)用像foo(1,2,3,4,5)。在foo()的主體中,param2是一個包含2-5的序列。
雙**表示可以有任意數(shù)量的額外命名參數(shù)。bar()可以調(diào)用像bar(1, a=2, b=3)。在bar()的主體中,param2是一個包含{'a':2,'b':3}的字典
使用以下代碼:
def foo(param1, *param2):
print(param1)
print(param2)
def bar(param1, **param2):
print(param1)
print(param2)
foo(1,2,3,4,5)
bar(1,a=2,b=3)
輸出是
1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}

TA貢獻1865條經(jīng)驗 獲得超7個贊
這是什么
**
(雙星)和*
(明星)的參數(shù)做
它們允許定義函數(shù)以接受并允許用戶傳遞任意數(shù)量的參數(shù),position(*
)和keyword(**
)。
定義功能
*args
允許任意數(shù)量的可選位置參數(shù)(參數(shù)),這些參數(shù)將分配給名為的元組args
。
**kwargs
允許任意數(shù)量的可選關(guān)鍵字參數(shù)(參數(shù)),這些參數(shù)將在名為dict的dict中kwargs
。
您可以(并且應(yīng)該)選擇任何適當?shù)拿Q,但是如果參數(shù)的目的是非特定語義,args
并且kwargs
是標準名稱。
擴展,傳遞任意數(shù)量的論點
您還可以分別使用*args
和**kwargs
傳遞列表(或任何可迭代)和dicts(或任何映射)中的參數(shù)。
接收參數(shù)的函數(shù)不必知道它們正在被擴展。
例如,Python 2的xrange沒有明確指望*args
,但因為它需要3個整數(shù)作為參數(shù):
>>> x = xrange(3) # create our *args - an iterable of 3 integers
>>> xrange(*x) # expand here
xrange(0, 2, 2)
再舉一個例子,我們可以使用dict擴展str.format:
>>> foo = 'FOO'
>>> bar = 'BAR'
>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())
'this is foo, FOO and bar, BAR'
Python 3中的新功能:使用僅關(guān)鍵字參數(shù)定義函數(shù)
您可以在- 之后只有關(guān)鍵字參數(shù)*args
- 例如,此處kwarg2
必須作為關(guān)鍵字參數(shù)給出 - 而不是位置:
def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs):
return arg, kwarg, args, kwarg2, kwargs
用法:
>>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz')
(1, 2, (3, 4, 5), 'kwarg2', {'bar': 'bar', 'baz': 'baz'})
此外,*可以單獨使用它來指示僅關(guān)鍵字參數(shù),而不允許無限制的位置參數(shù)。
def foo(arg, kwarg=None, *, kwarg2=None, **kwargs):
return arg, kwarg, kwarg2, kwargs
在這里,kwarg2同樣必須是一個顯式命名的關(guān)鍵字參數(shù):
>>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar')
(1, 2, 'kwarg2', {'foo': 'foo', 'bar': 'bar'})
我們不能再接受無限制的位置論證,因為我們沒有*args*:
>>> foo(1,2,3,4,5, kwarg2='kwarg2', foo='foo', bar='bar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() takes from 1 to 2 positional arguments
but 5 positional arguments (and 1 keyword-only argument) were given
同樣,更簡單地說,這里我們需要kwarg通過名稱給出,而不是位置:
def bar(*, kwarg=None):
return kwarg
在這個例子中,我們看到如果我們嘗試通過kwarg位置傳遞,我們會收到一個錯誤:
>>> bar('kwarg')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes 0 positional arguments but 1 was given
我們必須顯式地將kwarg參數(shù)作為關(guān)鍵字參數(shù)傳遞。
>>> bar(kwarg='kwarg')
'kwarg'
Python 2兼容演示
*args(通常說“star-args”)和**kwargs(明星可以通過說“kwargs”暗示,但明確表示“雙星kwargs”)是Python使用*和**表示法的常用習語。這些特定的變量名稱不是必需的(例如,您可以使用*foos和**bars),但偏離慣例可能會激怒您的Python同事。
當我們不知道我們的函數(shù)將接收什么或者我們可能傳遞多少個參數(shù)時,我們通常會使用這些,有時即使分別命名每個變量也會變得非?;靵y和冗余(但這種情況通常是明確的比隱含更好。
例1
以下函數(shù)描述了它們的使用方式,并演示了行為。請注意,命名b參數(shù)將在第二個位置參數(shù)之前使用:
def foo(a, b=10, *args, **kwargs):
'''
this function takes required argument a, not required keyword argument b
and any number of unknown positional arguments and keyword arguments after
'''
print('a is a required argument, and its value is {0}'.format(a))
print('b not required, its default value is 10, actual value: {0}'.format(b))
# we can inspect the unknown arguments we were passed:
# - args:
print('args is of type {0} and length {1}'.format(type(args), len(args)))
for arg in args:
print('unknown arg: {0}'.format(arg))
# - kwargs:
print('kwargs is of type {0} and length {1}'.format(type(kwargs),
len(kwargs)))
for kw, arg in kwargs.items():
print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))
# But we don't have to know anything about them
# to pass them to other functions.
print('Args or kwargs can be passed without knowing what they are.')
# max can take two or more positional args: max(a, b, c...)
print('e.g. max(a, b, *args) \n{0}'.format(
max(a, b, *args)))
kweg = 'dict({0})'.format( # named args same as unknown kwargs
', '.join('{k}={v}'.format(k=k, v=v)
for k, v in sorted(kwargs.items())))
print('e.g. dict(**kwargs) (same as {kweg}) returns: \n{0}'.format(
dict(**kwargs), kweg=kweg))
我們可以查看函數(shù)簽名的在線幫助help(foo),告訴我們
foo(a, b=10, *args, **kwargs)
我們用這個函數(shù)來調(diào)用 foo(1, 2, 3, 4, e=5, f=6, g=7)
打?。?/p>
a is a required argument, and its value is 1
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 2
unknown arg: 3
unknown arg: 4
kwargs is of type <type 'dict'> and length 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: g, arg: 7
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
4
e.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns:
{'e': 5, 'g': 7, 'f': 6}
例2
我們也可以使用我們剛剛提供的另一個函數(shù)來調(diào)用它a:
def bar(a):
b, c, d, e, f = 2, 3, 4, 5, 6
# dumping every local variable into foo as a keyword argument
# by expanding the locals dict:
foo(**locals())
bar(100) 打?。?/p>
a is a required argument, and its value is 100
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 0
kwargs is of type <type 'dict'> and length 4
unknown kwarg - kw: c, arg: 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: d, arg: 4
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
100
e.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns:
{'c': 3, 'e': 5, 'd': 4, 'f': 6}
例3:裝飾器中的實際用法
好吧,也許我們還沒有看到效用。因此,假設(shè)在差分代碼之前和/或之后,您有多個具有冗余代碼的函數(shù)。以下命名函數(shù)僅用于說明目的的偽代碼。
def foo(a, b, c, d=0, e=100):
# imagine this is much more code than a simple function call
preprocess()
differentiating_process_foo(a,b,c,d,e)
# imagine this is much more code than a simple function call
postprocess()
def bar(a, b, c=None, d=0, e=100, f=None):
preprocess()
differentiating_process_bar(a,b,c,d,e,f)
postprocess()
def baz(a, b, c, d, e, f):
... and so on
我們可能能夠以不同的方式處理這個問題,但我們當然可以使用裝飾器提取冗余,因此下面的示例演示了如何*args以及**kwargs非常有用:
def decorator(function):
'''function to wrap other functions with a pre- and postprocess'''
@functools.wraps(function) # applies module, name, and docstring to wrapper
def wrapper(*args, **kwargs):
# again, imagine this is complicated, but we only write it once!
preprocess()
function(*args, **kwargs)
postprocess()
return wrapper
現(xiàn)在,每個包裝的函數(shù)都可以更簡潔地編寫,因為我們已經(jīng)考慮了冗余:
@decorator
def foo(a, b, c, d=0, e=100):
differentiating_process_foo(a,b,c,d,e)
@decorator
def bar(a, b, c=None, d=0, e=100, f=None):
differentiating_process_bar(a,b,c,d,e,f)
@decorator
def baz(a, b, c=None, d=0, e=100, f=None, g=None):
differentiating_process_baz(a,b,c,d,e,f, g)
@decorator
def quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):
differentiating_process_quux(a,b,c,d,e,f,g,h)
通過分解我們的代碼*args并**kwargs允許我們這樣做,我們減少了代碼行數(shù),提高了可讀性和可維護性,并在程序中為邏輯提供了唯一的規(guī)范位置。如果我們需要改變這個結(jié)構(gòu)的任何部分,我們有一個地方可以進行每次更改。

TA貢獻1776條經(jīng)驗 獲得超12個贊
讓我們首先了解什么是位置參數(shù)和關(guān)鍵字參數(shù)。下面是使用Positional參數(shù)的函數(shù)定義示例。
def test(a,b,c):
print(a)
print(b)
print(c)
test(1,2,3)
#output:
1
2
3
所以這是一個帶位置參數(shù)的函數(shù)定義。您也可以使用關(guān)鍵字/命名參數(shù)調(diào)用它:
def test(a,b,c):
print(a)
print(b)
print(c)
test(a=1,b=2,c=3)
#output:
1
2
3
現(xiàn)在讓我們用關(guān)鍵字參數(shù)研究函數(shù)定義的示例:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(a=1,b=2,c=3)
#output :
1
2
3
-------------------------
您也可以使用位置參數(shù)調(diào)用此函數(shù):
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(1,2,3)
# output :
1
2
3
---------------------------------
所以我們現(xiàn)在知道具有位置和關(guān)鍵字參數(shù)的函數(shù)定義。
現(xiàn)在讓我們研究'*'運算符和'**'運算符。
請注意,這些運營商可以在兩個方面使用:
a)函數(shù)調(diào)用
b)功能定義
在函數(shù)調(diào)用中使用'*'運算符和'**'運算符。
讓我們直接舉一個例子然后討論它。
def sum(a,b): #receive args from function calls as sum(1,2) or sum(a=1,b=2)
print(a+b)
my_tuple = (1,2)
my_list = [1,2]
my_dict = {'a':1,'b':2}
# Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator
sum(*my_tuple) # becomes same as sum(1,2) after unpacking my_tuple with '*'
sum(*my_list) # becomes same as sum(1,2) after unpacking my_list with '*'
sum(**my_dict) # becomes same as sum(a=1,b=2) after unpacking by '**'
# output is 3 in all three calls to sum function.
所以記住
在函數(shù)調(diào)用中使用'*'或'**'運算符時-
'*'運算符將數(shù)據(jù)結(jié)構(gòu)(如列表或元組)解包為函數(shù)定義所需的參數(shù)。
'**'運算符將字典解包為函數(shù)定義所需的參數(shù)。
現(xiàn)在讓我們研究函數(shù)定義中的'*'運算符。例:
def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4))
sum = 0
for a in args:
sum+=a
print(sum)
sum(1,2,3,4) #positional args sent to function sum
#output:
10
在函數(shù)定義中,'*'運算符將接收的參數(shù)打包到元組中。
現(xiàn)在讓我們看一下函數(shù)定義中使用的'**'的示例:
def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4})
sum=0
for k,v in args.items():
sum+=v
print(sum)
sum(a=1,b=2,c=3,d=4) #positional args sent to function sum
在函數(shù)定義中,'**'運算符將接收的參數(shù)打包到字典中。
所以請記?。?/p>
在函數(shù)調(diào)用中,'*' 將元組或列表的數(shù)據(jù)結(jié)構(gòu)解包為要由函數(shù)定義接收的位置或關(guān)鍵字參數(shù)。
在函數(shù)調(diào)用中,'**' 將字典的數(shù)據(jù)結(jié)構(gòu)解包為要由函數(shù)定義接收的位置或關(guān)鍵字參數(shù)。
在函數(shù)定義中,'*' 將位置參數(shù)打包到元組中。
在函數(shù)定義中,'**' 將關(guān)鍵字參數(shù)打包到字典中。
添加回答
舉報