Tod*_*odd 2149 python syntax parameter-passing variadic-functions argument-unpacking
在下面的方法定义,什么是*
和**
为做param2
?
def foo(param1, *param2):
def bar(param1, **param2):
Run Code Online (Sandbox Code Playgroud)
Pet*_*ann 2045
的*args
和**kwargs
是一种常见的成语,以允许参数,以作为部分所述功能的任意数量的多个上定义函数 Python文档英寸
该*args
给你的所有函数参数为一个元组:
In [1]: def foo(*args):
...: for a in args:
...: print a
...:
...:
In [2]: foo(1)
1
In [4]: foo(1,2,3)
1
2
3
Run Code Online (Sandbox Code Playgroud)
该**kwargs
会给你所有的
关键字参数除了那些与作为字典的形式参数.
In [5]: def bar(**kwargs):
...: for a in kwargs:
...: print a, kwargs[a]
...:
...:
In [6]: bar(name='one', age=27)
age 27
name one
Run Code Online (Sandbox Code Playgroud)
这两个习语可以与普通参数混合使用,以允许一组固定和一些变量参数:
def foo(kind, *args, **kwargs):
pass
Run Code Online (Sandbox Code Playgroud)
*l
习惯用法的另一个用法是在调用函数时解包参数列表.
In [9]: def foo(bar, lee):
...: print bar, lee
...:
...:
In [10]: l = [1,2]
In [11]: foo(*l)
1 2
Run Code Online (Sandbox Code Playgroud)
在Python 3中,可以*l
在赋值的左侧使用(Extended Iterable Unpacking),尽管在此上下文中它给出了一个列表而不是一个元组:
first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
Run Code Online (Sandbox Code Playgroud)
Python 3也增加了新的语义(参考PEP 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
Run Code Online (Sandbox Code Playgroud)
这样的函数只接受3个位置参数,后面的所有内容*
只能作为关键字参数传递.
Lor*_*ein 582
值得注意的是,您也可以使用*
和**
调用函数.这是一个快捷方式,允许您使用列表/元组或字典直接将多个参数传递给函数.例如,如果您具有以下功能:
def foo(x,y,z):
print("x=" + str(x))
print("y=" + str(y))
print("z=" + str(z))
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
>>> 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
Run Code Online (Sandbox Code Playgroud)
注意:键的名称mydict
必须与函数的参数完全相同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'
Run Code Online (Sandbox Code Playgroud)
nic*_*ckd 167
单*表示可以有任意数量的额外位置参数.foo()
可以调用像foo(1,2,3,4,5)
.在foo()的主体中,param2是一个包含2-5的序列.
双**表示可以有任意数量的额外命名参数.bar()
可以调用像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)
Run Code Online (Sandbox Code Playgroud)
输出是
1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}
Run Code Online (Sandbox Code Playgroud)
Aar*_*all 131
这是什么
**
(双星)和*
(明星)的参数做
它们允许定义函数以接受并允许用户传递任意数量的参数,position(*
)和keyword(**
).
*args
允许任意数量的可选位置参数(参数),这些参数将分配给名为的元组args
.
**kwargs
允许任意数量的可选关键字参数(参数),这些参数将在名为dict的dict中kwargs
.
您可以(并且应该)选择任何适当的名称,但是如果参数的目的是非特定语义,args
并且kwargs
是标准名称.
您还可以分别使用*args
和**kwargs
传递列表(或任何可迭代)和dicts(或任何映射)中的参数.
接收参数的函数不必知道它们正在被扩展.
例如,Python 2的xrange没有明确指望*args
,但因为它需要3个整数作为参数:
>>> x = xrange(3) # create our *args - an iterable of 3 integers
>>> xrange(*x) # expand here
xrange(0, 2, 2)
Run Code Online (Sandbox Code Playgroud)
再举一个例子,我们可以使用dict扩展str.format
:
>>> foo = 'FOO'
>>> bar = 'BAR'
>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())
'this is foo, FOO and bar, BAR'
Run Code Online (Sandbox Code Playgroud)
您可以在- 之后只有关键字参数*args
- 例如,此处kwarg2
必须作为关键字参数给出 - 而不是位置:
def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs):
return arg, kwarg, args, kwarg2, kwargs
Run Code Online (Sandbox Code Playgroud)
用法:
>>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz')
(1, 2, (3, 4, 5), 'kwarg2', {'bar': 'bar', 'baz': 'baz'})
Run Code Online (Sandbox Code Playgroud)
此外,*
可以单独使用它来指示仅关键字参数,而不允许无限制的位置参数.
def foo(arg, kwarg=None, *, kwarg2=None, **kwargs):
return arg, kwarg, kwarg2, kwargs
Run Code Online (Sandbox Code Playgroud)
在这里,kwarg2
同样必须是一个显式命名的关键字参数:
>>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar')
(1, 2, 'kwarg2', {'foo': 'foo', 'bar': 'bar'})
Run Code Online (Sandbox Code Playgroud)
我们不能再接受无限制的位置论证,因为我们没有*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
Run Code Online (Sandbox Code Playgroud)
同样,更简单地说,这里我们需要kwarg
通过名称给出,而不是位置:
def bar(*, kwarg=None):
return kwarg
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我们看到如果我们尝试通过kwarg
位置传递,我们会收到一个错误:
>>> bar('kwarg')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes 0 positional arguments but 1 was given
Run Code Online (Sandbox Code Playgroud)
我们必须显式地将kwarg
参数作为关键字参数传递.
>>> bar(kwarg='kwarg')
'kwarg'
Run Code Online (Sandbox Code Playgroud)
*args
(通常说"star-args")和**kwargs
(星形可以通过说"kwargs"暗示,但明确表示"双星kwargs")是Python使用*
和**
表示法的常用习语.这些特定的变量名称不是必需的(例如,您可以使用*foos
和**bars
),但偏离惯例可能会激怒您的Python同事.
当我们不知道我们的函数将接收什么或者我们可能传递多少个参数时,我们通常会使用这些,有时即使分别命名每个变量也会变得非常混乱和冗余(但这种情况通常是明确的比隐含更好.
例1
以下函数描述了它们的使用方式,并演示了行为.请注意,命名b
参数将在第二个位置参数之前使用:
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))
Run Code Online (Sandbox Code Playgroud)
我们可以查看函数签名的在线帮助help(foo)
,告诉我们
foo(a, b=10, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
我们用这个函数来调用 foo(1, 2, 3, 4, e=5, f=6, g=7)
打印:
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}
Run Code Online (Sandbox Code Playgroud)
例2
我们也可以使用我们刚刚提供的另一个函数来调用它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())
Run Code Online (Sandbox Code Playgroud)
bar(100)
打印:
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}
Run Code Online (Sandbox Code Playgroud)
例3:装饰器中的实际用法
好吧,也许我们还没有看到效用.因此,假设在差分代码之前和/或之后,您有多个具有冗余代码的函数.以下命名函数仅用于说明目的的伪代码.
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
Run Code Online (Sandbox Code Playgroud)
我们可能能够以不同的方式处理这个问题,但我们当然可以使用装饰器提取冗余,因此下面的示例演示了如何*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
Run Code Online (Sandbox Code Playgroud)
现在,每个包装函数都可以更简洁地编写,因为我们已经考虑了冗余:
@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)
Run Code Online (Sandbox Code Playgroud)
通过分解我们的代码*args
并**kwargs
允许我们这样做,我们减少了代码行数,提高了可读性和可维护性,并在程序中为逻辑提供了唯一的规范位置.如果我们需要改变这个结构的任何部分,我们有一个地方可以进行每次更改.
Kar*_*uja 45
让我们首先了解什么是位置参数和关键字参数.下面是使用Positional参数的函数定义示例.
def test(a,b,c):
print(a)
print(b)
print(c)
test(1,2,3)
#output:
1
2
3
Run Code Online (Sandbox Code Playgroud)
所以这是一个带位置参数的函数定义.您也可以使用关键字/命名参数调用它:
def test(a,b,c):
print(a)
print(b)
print(c)
test(a=1,b=2,c=3)
#output:
1
2
3
Run Code Online (Sandbox Code Playgroud)
现在让我们用关键字参数研究函数定义的示例:
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
-------------------------
Run Code Online (Sandbox Code Playgroud)
您也可以使用位置参数调用此函数:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print('-------------------------')
test(1,2,3)
# output :
1
2
3
---------------------------------
Run Code Online (Sandbox Code Playgroud)
所以我们现在知道具有位置和关键字参数的函数定义.
现在让我们研究'*'运算符和'**'运算符.
请注意,这些运营商可以在两个方面使用:
a)函数调用
b)功能定义
在函数调用中使用'*'运算符和'**'运算符.
让我们直接举一个例子然后讨论它.
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.
Run Code Online (Sandbox Code Playgroud)
所以记住
在函数调用中使用'*'或'**'运算符时-
'*'运算符将数据结构(如列表或元组)解包为函数定义所需的参数.
'**'运算符将字典解包为函数定义所需的参数.
现在让我们研究函数定义中的'*'运算符.例:
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
Run Code Online (Sandbox Code Playgroud)
在函数定义中,'*'运算符将接收的参数打包到元组中.
现在让我们看一下函数定义中使用的'**'的示例:
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
Run Code Online (Sandbox Code Playgroud)
在函数定义中,'**'运算符将接收的参数打包到字典中.
所以请记住:
在函数调用中,'*' 将元组或列表的数据结构解包为要由函数定义接收的位置或关键字参数.
在函数调用中,'**' 将字典的数据结构解包为要由函数定义接收的位置或关键字参数.
在函数定义中,'*' 将位置参数打包到元组中.
在函数定义中,'**' 将关键字参数打包到字典中.
Bra*_*mon 24
虽然在Python 3中扩展了对星/ splat运算符的使用,但我喜欢下表,因为它与这些运算符与函数的使用有关.splat运算符既可以在函数构造中使用,也可以在函数调用中使用:
In function construction In function call
=======================================================================
| def f(*args): | def f(a, b):
*args | for arg in args: | return a + b
| print(arg) | args = (1, 2)
| f(1, 2) | f(*args)
----------|--------------------------------|---------------------------
| def f(a, b): | def f(a, b):
**kwargs | return a + b | return a + b
| def g(**kwargs): | kwargs = dict(a=1, b=2)
| return f(**kwargs) | f(**kwargs)
| g(a=1, b=2) |
-----------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
这真的只是总结了Lorin Hochstein的答案,但我觉得它很有帮助.
Mil*_*uss 16
*
是让您能够定义一个函数,该函数可以将任意数量的参数作为列表提供(例如f(*myList)
).**
是让您能够通过提供字典(例如f(**{'x' : 1, 'y' : 2})
)来提供函数的参数.让我们定义一个函数,它接受两个正常变量显示此x
,y
以及可以接受更多的论据myArgs
,并能接受更多的论据myKW
.稍后,我们将展示如何y
使用myArgDict
.
def f(x, y, *myArgs, **myKW):
print("# x = {}".format(x))
print("# y = {}".format(y))
print("# myArgs = {}".format(myArgs))
print("# myKW = {}".format(myKW))
print("# ----------------------------------------------------------------------")
# Define a list for demonstration purposes
myList = ["Left", "Right", "Up", "Down"]
# Define a dictionary for demonstration purposes
myDict = {"Wubba": "lubba", "Dub": "dub"}
# Define a dictionary to feed y
myArgDict = {'y': "Why?", 'y0': "Why not?", "q": "Here is a cue!"}
# The 1st elem of myList feeds y
f("myEx", *myList, **myDict)
# x = myEx
# y = Left
# myArgs = ('Right', 'Up', 'Down')
# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------
# y is matched and fed first
# The rest of myArgDict becomes additional arguments feeding myKW
f("myEx", **myArgDict)
# x = myEx
# y = Why?
# myArgs = ()
# myKW = {'y0': 'Why not?', 'q': 'Here is a cue!'}
# ----------------------------------------------------------------------
# The rest of myArgDict becomes additional arguments feeding myArgs
f("myEx", *myArgDict)
# x = myEx
# y = y
# myArgs = ('y0', 'q')
# myKW = {}
# ----------------------------------------------------------------------
# Feed extra arguments manually and append even more from my list
f("myEx", 4, 42, 420, *myList, *myDict, **myDict)
# x = myEx
# y = 4
# myArgs = (42, 420, 'Left', 'Right', 'Up', 'Down', 'Wubba', 'Dub')
# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}
# ----------------------------------------------------------------------
# Without the stars, the entire provided list and dict become x, and y:
f(myList, myDict)
# x = ['Left', 'Right', 'Up', 'Down']
# y = {'Wubba': 'lubba', 'Dub': 'dub'}
# myArgs = ()
# myKW = {}
# ----------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
**
专门用于词典.**
必须*
始终遵循.Mey*_*ghi 16
TL; 博士
以下是6种不同的使用情况*
,并**
在Python编程:
*args
:接受任意数量的位置参数 def foo(*args): pass
,这里foo
接受任意数量的位置参数,即以下调用是有效的foo(1)
,foo(1, 'bar')
**kwargs
:接受任意数量的关键字参数 def foo(**kwargs): pass
,此处 'foo' 接受任意数量的关键字参数,即以下调用是有效的foo(name='Tom')
,foo(name='Tom', age=33)
*args, **kwargs
:接受任意数量的位置和关键字参数 def foo(*args, **kwargs): pass
,这里foo
接受任意数量的位置和关键字参数,即以下调用是有效的foo(1,name='Tom')
,foo(1, 'bar', name='Tom', age=33)
*
:强制仅使用关键字参数 def foo(pos1, pos2, *, kwarg1): pass
,这里*
意味着 foo 只接受 pos2 之后的关键字参数,因此foo(1, 2, 3)
会引发 TypeError 但没问题foo(1, 2, kwarg1=3)
。*_
(注意:这只是一个约定): def foo(bar, baz, *_): pass
意味着(按照约定)foo
仅在其工作中使用bar
和baz
参数,而将忽略其他参数。\**_
(注意:这只是一个约定): def foo(bar, baz, **_): pass
意味着(按照约定)foo
仅在其工作中使用bar
和baz
参数,而将忽略其他参数。奖励:从 python 3.8 开始,可以/
在函数定义中使用来强制执行位置参数。在下面的示例中,参数 a 和 b 是仅位置参数,而 c 或 d 可以是位置或关键字,而 e 或 f 必须是关键字:
def f(a, b, /, c, d, *, e, f):
pass
Run Code Online (Sandbox Code Playgroud)
Chr*_*rch 12
从Python文档:
如果存在比正式参数槽更多的位置参数,则会引发TypeError异常,除非存在使用语法"*identifier"的形式参数; 在这种情况下,该形式参数接收包含多余位置参数的元组(或者如果没有多余的位置参数则为空元组).
如果任何关键字参数与形式参数名称不对应,则引发TypeError异常,除非存在使用语法"**identifier"的形式参数; 在这种情况下,该形式参数接收包含多余关键字参数的字典(使用关键字作为键,参数值作为对应值),或者如果没有多余的关键字参数则接收(新)空字典.
在Python 3.5,你还可以在使用这个语法list
,dict
,tuple
,和set
显示器(有时也称为文本).请参阅PEP 488:其他拆包概括.
>>> (0, *range(1, 4), 5, *range(6, 8))
(0, 1, 2, 3, 5, 6, 7)
>>> [0, *range(1, 4), 5, *range(6, 8)]
[0, 1, 2, 3, 5, 6, 7]
>>> {0, *range(1, 4), 5, *range(6, 8)}
{0, 1, 2, 3, 5, 6, 7}
>>> d = {'one': 1, 'two': 2, 'three': 3}
>>> e = {'six': 6, 'seven': 7}
>>> {'zero': 0, **d, 'five': 5, **e}
{'five': 5, 'seven': 7, 'two': 2, 'one': 1, 'three': 3, 'six': 6, 'zero': 0}
Run Code Online (Sandbox Code Playgroud)
它还允许在单个函数调用中解压缩多个迭代.
>>> range(*[1, 10], *[2])
range(1, 10, 2)
Run Code Online (Sandbox Code Playgroud)
(感谢mgilson的PEP链接.)
小智 7
我想举一个其他人没有提到过的例子
*也可以拆开发电机包装
Python3文档中的一个示例
x = [1, 2, 3]
y = [4, 5, 6]
unzip_x, unzip_y = zip(*zip(x, y))
Run Code Online (Sandbox Code Playgroud)
unzip_x将是[1,2,3],unzip_y将是[4,5,6]
zip()接收多个iretable args,并返回一个生成器.
zip(*zip(x,y)) -> zip((1, 4), (2, 5), (3, 6))
Run Code Online (Sandbox Code Playgroud)
它包传递给函数的参数将list
和dict
分别在函数体中。当您定义这样的函数签名时:
def func(*args, **kwds):
# do stuff
Run Code Online (Sandbox Code Playgroud)
可以使用任意数量的参数和关键字参数调用它。非关键字参数被打包到args
函数体内部调用的列表中,关键字参数被打包到kwds
函数体内部调用的字典中。
func("this", "is a list of", "non-keyowrd", "arguments", keyword="ligma", options=[1,2,3])
Run Code Online (Sandbox Code Playgroud)
现在在函数体内,当函数被调用时,有两个局部变量,args
一个是有值的列表["this", "is a list of", "non-keyword", "arguments"]
,kwds
另一个是dict
有值的{"keyword" : "ligma", "options" : [1,2,3]}
这也适用于相反的情况,即从调用方。例如,如果您有一个函数定义为:
def f(a, b, c, d=1, e=10):
# do stuff
Run Code Online (Sandbox Code Playgroud)
你可以通过解包你在调用范围内的迭代或映射来调用它:
iterable = [1, 20, 500]
mapping = {"d" : 100, "e": 3}
f(*iterable, **mapping)
# That call is equivalent to
f(1, 20, 500, d=100, e=3)
Run Code Online (Sandbox Code Playgroud)
基于 nickd 的回答......
def foo(param1, *param2):
print(param1)
print(param2)
def bar(param1, **param2):
print(param1)
print(param2)
def three_params(param1, *param2, **param3):
print(param1)
print(param2)
print(param3)
foo(1, 2, 3, 4, 5)
print("\n")
bar(1, a=2, b=3)
print("\n")
three_params(1, 2, 3, 4, s=5)
Run Code Online (Sandbox Code Playgroud)
输出:
1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}
1
(2, 3, 4)
{'s': 5}
Run Code Online (Sandbox Code Playgroud)
基本上,任何数量的位置参数都可以使用 *args,任何命名参数(或 kwargs aka 关键字参数)都可以使用 **kwargs。
*
表示将可变参数作为元组接收
**
表示将可变参数作为字典接收
使用方式如下:
1)单*
def foo(*args):
for arg in args:
print(arg)
foo("two", 3)
Run Code Online (Sandbox Code Playgroud)
输出:
two
3
Run Code Online (Sandbox Code Playgroud)
2)现在 **
def bar(**kwargs):
for key in kwargs:
print(key, kwargs[key])
bar(dic1="two", dic2=3)
Run Code Online (Sandbox Code Playgroud)
输出:
dic1 two
dic2 3
Run Code Online (Sandbox Code Playgroud)
除函数调用外,* args和** kwargs在类层次结构中很有用,并且还避免了必须__init__
在Python中编写方法。在类似Django代码的框架中可以看到类似的用法。
例如,
def __init__(self, *args, **kwargs):
for attribute_name, value in zip(self._expected_attributes, args):
setattr(self, attribute_name, value)
if kwargs.has_key(attribute_name):
kwargs.pop(attribute_name)
for attribute_name in kwargs.viewkeys():
setattr(self, attribute_name, kwargs[attribute_name])
Run Code Online (Sandbox Code Playgroud)
子类可以是
class RetailItem(Item):
_expected_attributes = Item._expected_attributes + ['name', 'price', 'category', 'country_of_origin']
class FoodItem(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['expiry_date']
Run Code Online (Sandbox Code Playgroud)
然后将该子类实例化为
food_item = FoodItem(name = 'Jam',
price = 12.0,
category = 'Foods',
country_of_origin = 'US',
expiry_date = datetime.datetime.now())
Run Code Online (Sandbox Code Playgroud)
此外,具有仅对该子类实例有意义的新属性的子类可以调用Base类__init__
以卸载属性设置。这是通过* args和** kwargs完成的。主要使用kwargs,以便使用命名参数可以读取代码。例如,
class ElectronicAccessories(RetailItem):
_expected_attributes = RetailItem._expected_attributes + ['specifications']
# Depend on args and kwargs to populate the data as needed.
def __init__(self, specifications = None, *args, **kwargs):
self.specifications = specifications # Rest of attributes will make sense to parent class.
super(ElectronicAccessories, self).__init__(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
可以被形容为
usb_key = ElectronicAccessories(name = 'Sandisk',
price = '$6.00',
category = 'Electronics',
country_of_origin = 'CN',
specifications = '4GB USB 2.0/USB 3.0')
Run Code Online (Sandbox Code Playgroud)
完整的代码在这里
给定一个具有 3 个项目作为参数的函数
sum = lambda x, y, z: x + y + z
sum(1,2,3) # sum 3 items
sum([1,2,3]) # error, needs 3 items, not 1 list
x = [1,2,3][0]
y = [1,2,3][1]
z = [1,2,3][2]
sum(x,y,z) # ok
sum(*[1,2,3]) # ok, 1 list becomes 3 items
Run Code Online (Sandbox Code Playgroud)
想象一下这个玩具有一个袋子,里面有三角形、圆形和矩形物品。那个包不能直接放。您需要打开袋子才能取出这 3 件物品,现在它们就装好了。Python * 运算符执行此解包过程。
归档时间: |
|
查看次数: |
651099 次 |
最近记录: |