*args
和**kwargs
在这些函数定义中是什么意思?
def foo(x, y, *args):
pass
def bar(x, y, **kwargs):
pass
请参阅**(双星/星号)和*(星号/星号)在函数调用中是什么意思?关于参数的补充问题。
*args
和**kwargs
在这些函数定义中是什么意思?
def foo(x, y, *args):
pass
def bar(x, y, **kwargs):
pass
请参阅**(双星/星号)和*(星号/星号)在函数调用中是什么意思?关于参数的补充问题。
*args
和**kwargs
是一种常见的习惯用法,允许函数有任意数量的参数,如在Python文档中定义函数的更多信息。
*参数
将为您提供所有函数参数列为元组:
def foo(*args):
for a in args:
print(a)
foo(1)
# 1
foo(1,2,3)
# 1
# 2
# 3
The **kwargs
will give you all
keyword arguments except for those corresponding to a formal parameter as a dictionary.
def bar(**kwargs):
for a in kwargs:
print(a, kwargs[a])
bar(name= one , age=27)
# name one
# age 27
这两种习惯用法都可以与普通参数混合使用,以允许一组固定参数和一些可变参数:
def foo(kind, *args, **kwargs):
pass
也可以反过来使用:
def foo(a, b, c):
print(a, b, c)
obj = { b :10, c : lee }
foo(100,**obj)
# 100 10 lee
*l
习惯用法的另一个用法是在调用函数时解压缩参数列表。
def foo(bar, lee):
print(bar, lee)
l = [1,2]
foo(*l)
# 1 2
在Python 3中,可以在赋值的左侧使用*l
(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
例如,以下内容适用于python 3,但不适用于python 2:
>>> x = [1, 2]
>>> [*x]
[1, 2]
>>> [*x, 3, 4]
[1, 2, 3, 4]
>>> x = {1:1, 2:2}
>>> x
{1: 1, 2: 2}
>>> {**x, 3:3, 4:4}
{1: 1, 2: 2, 3: 3, 4: 4}
这样的函数只接受3个位置参数,*
之后的所有内容只能作为关键字参数传递。
dict
, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order.**kwargs
now corresponds to the order in which keyword arguments were passed to the function." - What’s New In Python 3.6同样值得注意的是,在调用函数时也可以使用*
和**
。这是一个快捷方式,允许您使用列表/元组或字典直接向函数传递多个参数。例如,如果您具有以下功能:
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
中的键的命名必须与函数foo
的参数完全相同。否则,它将抛出一个<code>TypeError</code>:
>>> 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
单个*表示可以有任意数量的额外位置参数foo()
可以像foo(1,2,3,4,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)
输出为
1
(2, 3, 4, 5)
1
{ a : 2, b : 3}
What does
**
(double star) and*
(star) do for parameters?
它们允许将函数定义为接受,并允许用户传递任意数量的参数、位置(*
)和关键字(*
*args
允许任意数量的可选位置参数(参数),这些参数将被分配给名为args
的元组。
**kwargs
允许任意数量的可选关键字参数(参数),这些参数将位于名为kwargs[/code>的dict中。
您可以(也应该)选择任何合适的名称,但如果意图使参数具有非特定语义,则args
和kwargs
是标准名称。
您还可以使用*args
和**kwargs
分别从列表(或任何可迭代的)和dicts(或任何映射)传递参数。
接收参数的函数不必知道它们正在被扩展。
例如,Python 2的xrange并没有显式地期望<code>*args</code>,但因为它采用3个整数作为参数:
>>> x = xrange(3) # create our *args - an iterable of 3 integers
>>> xrange(*x) # expand here
xrange(0, 2, 2)
作为另一个例子,我们可以在<code>str.format</code>中使用dict扩展:
>>> foo = FOO
>>> bar = BAR
>>> this is foo, {foo} and bar, {bar} .format(**locals())
this is foo, FOO and bar, BAR
您可以拥有在*args
之后的仅关键字参数-例如,在这里,kwarg2
必须作为关键字参数给出,而不是位置:
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 })
此外,<code>*</code>本身可以用于指示后面跟着仅关键字的参数,而不允许不受限制的位置参数。
def foo(arg, kwarg=None, *, kwarg2=None, **kwargs):
return arg, kwarg, kwarg2, kwargs
这里,kwarg2
再次必须是显式命名的关键字参数:
>>> 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
参数作为关键字参数。
>>> bar(kwarg= kwarg )
kwarg
*args
(通常称为“星形args”)和**kwargs
(星形可以通过说“kwargs”来暗示,但可以用“双星kwargs“来明确)是Python使用*
和*
表示法的常见习惯用法。这些特定的变量名是不需要的(例如,您可以使用*foos
和**bars
当我们不知道函数将接收什么或可能传递多少参数时,我们通常会使用这些参数,有时甚至当单独命名每个变量时,也会变得非常混乱和多余(但在这种情况下,通常显式比隐式更好)。
示例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)
{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:
{0} .format(
dict(**kwargs), kweg=kweg))
我们可以通过help(foo)
查看函数签名的在线帮助,它告诉我们
foo(a, b=10, *args, **kwargs)
让我们用<code>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}
示例2
我们也可以使用另一个函数来调用它,我们只需在其中提供一个
:
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())
条形图(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}
示例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
我们可能能够以不同的方式处理这一问题,但我们当然可以使用装饰器提取冗余,因此下面的示例演示了*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
现在,每个封装的函数都可以写得更简洁,因为我们已经考虑到了冗余:
@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
允许我们这样做),我们减少了代码行,提高了可读性和可维护性,并为程序中的逻辑提供了唯一的规范位置。如果我们需要改变这个结构的任何部分,我们都有一个地方可以进行每一次改变。
Let us first understand what are positional arguments and keyword arguments. Below is an example of function definition with Positional arguments.
def test(a,b,c):
print(a)
print(b)
print(c)
test(1,2,3)
#output:
1
2
3
So this is a function definition with positional arguments. You can call it with keyword/named arguments as well:
def test(a,b,c):
print(a)
print(b)
print(c)
test(a=1,b=2,c=3)
#output:
1
2
3
现在,让我们研究一个使用关键字参数的函数定义示例:
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
-------------------------
您也可以使用位置参数调用此函数:
def test(a=0,b=0,c=0):
print(a)
print(b)
print(c)
print( ------------------------- )
test(1,2,3)
# output :
1
2
3
---------------------------------
因此,我们现在知道了带有位置参数和关键字参数的函数定义。
现在让我们研究*运算符和**运算符。
请注意,这些运算符可用于两个区域:
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.
所以请记住
在函数调用中使用*或**运算符时-
*运算符将数据结构(如列表或元组)解包到函数定义所需的参数中。
**运算符将字典解包到函数定义所需的参数中。
Now let us study the * operator use in function definition. Example:
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
在函数定义中,*运算符将接收到的参数打包到元组中。
现在让我们看看函数定义中使用的**示例:
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
在函数定义中,**运算符将接收到的参数打包到字典中。
所以请记住:
在函数调用中,*将元组或列表的数据结构解压缩为函数定义要接收的位置或关键字参数。
在函数调用中,**将字典的数据结构解压缩为函数定义要接收的位置参数或关键字参数。
在函数定义中,*将位置参数打包到元组中。
在函数定义中,**将关键字参数打包到字典中。
此表便于在函数构造和函数调用中使用*
和**
:
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) |
-----------------------------------------------------------------------
这真的只是用来总结Lorin Hochstein的回答,但我觉得这很有帮助。
与此相关:星号/splat运算符的用途已被在Python 3中扩展
TL;灾难恢复
以下是python编程中*
和**
的6种不同用例:
*args
: def foo(*args): pass
, here foo
accepts any number of positional arguments, i. e., the following calls are valid foo(1)
, foo(1, bar )
**kwargs
: def foo(**kwargs): pass
, here foo accepts any number of keyword arguments, i. e., the following calls are valid foo(name= Tom )
, foo(name= Tom , age=33)
*args, **kwargs
: def foo(*args, **kwargs): pass
, here foo
accepts any number of positional and keyword arguments, i. e., the following calls are valid foo(1,name= Tom )
, foo(1, bar , name= Tom , age=33)
*
: def foo(pos1, pos2, *, kwarg1): pass
, here *
means that foo only accept keyword arguments after pos2, hence foo(1, 2, 3)
raises TypeError but foo(1, 2, kwarg1=3)
is ok.*_
(Note: this is a convention only): def foo(bar, baz, *_): pass
means (by convention) foo
only uses bar
and baz
arguments in its working and will ignore others.**_
(Note: this is a convention only): def foo(bar, baz, **_): pass
means (by convention) foo
only uses bar
and baz
arguments in its working and will ignore others.优点:从python 3.8开始,可以在函数定义中使用/
来强制执行仅位置参数。在以下示例中,参数a和b仅为位置,而c或d可以是位置或关键字,e或f必须是关键字:
def f(a, b, /, c, d, *, e, f):
pass
*
and **
have special usage in the function argument list. *
implies that the argument is a list and **
implies that the argument
is a dictionary. This allows functions to take arbitrary number of
arguments
*
is to give you the ability to define a function that can take an arbitrary number of arguments provided as a list (e.g. f(*myList)
).**
is to give you the ability to feed a function s arguments by providing a dictionary (e.g. f(**{ x : 1, y : 2})
).让我们通过定义一个函数来展示这一点,该函数接受两个正常变量x
、y
,并且可以接受更多的参数作为myArgs
;还可以接受更多参数作为myKW
。稍后,我们将展示如何使用myArgDict
馈送y
。
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 = {}
# ----------------------------------------------------------------------
**
is exclusively reserved for dictionaries.**
must come after *
, always.从Python文档中:
如果位置参数的数量多于形式参数槽的数量,则会引发TypeError异常,除非存在使用语法“*identifier”的形式参数;在这种情况下,该形式参数接收一个包含多余位置参数的元组(如果没有多余位置参数,则接收一个空元组)。
如果任何关键字参数与正式参数名称不对应,则会引发TypeError异常,除非存在使用语法“**标识符”的正式参数;在这种情况下,该形式参数接收一个包含多余关键字参数的字典(使用关键字作为关键字,参数值作为相应值),或者如果没有多余关键字参数,则接收一个(新的)空字典。
*
表示接收变量参数作为元组
**
表示将变量参数作为字典接收
按如下方式使用:
1)单个*
def foo(*args):
for arg in args:
print(arg)
foo("two", 3)
输出:
two
3
2)现在**
def bar(**kwargs):
for key in kwargs:
print(key, kwargs[key])
bar(dic1="two", dic2=3)
输出:
dic1 two
dic2 3
在Python 3.5中,您还可以在<code>list</code>、<code>dict</code>、<code<tuple</code>和<code>set</code<display(有时也称为文字)中使用此语法。请参阅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}
它还允许在单个函数调用中对多个可迭代项进行解包。
>>> range(*[1, 10], *[2])
range(1, 10, 2)
(感谢mgilson提供的政治公众人物链接。)
它将传递给函数的参数分别打包到函数体内的list
和dict
中。当您定义这样的函数签名时:
def func(*args, **kwds):
# do stuff
它可以用任意数量的参数和关键字参数调用。非关键字参数被打包到函数体内一个名为<code>args</code>的列表中,关键字参数被包装到函数体内部一个名叫<code>kwds</code<的dict中。
func("this", "is a list of", "non-keyowrd", "arguments", keyword="ligma", options=[1,2,3])
现在,在函数体内部,当调用函数时,有两个局部变量,args
,这是一个值为[“this”的列表,“是一个”、“non-keyword”、“arguments”的列表
和kwds
的列表,它是一个dict,值为
{“keyword”:“ligma”,“options”:[1,2,3]}
这也起到了相反的作用,即从呼叫方开始。例如,如果您将一个函数定义为:
def f(a, b, c, d=1, e=10):
# do stuff
您可以通过拆包调用范围中的可迭代项或映射来调用它:
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)
我想举一个别人没有提到的例子
*还可以打开生成器
Python3文档中的一个示例
x = [1, 2, 3]
y = [4, 5, 6]
unzip_x, unzip_y = zip(*zip(x, y))
unzip _x将为(1,2,3),unzip _y将为(4,5,6)
zip()接收多个iretable参数,并返回一个生成器。
zip(*zip(x,y)) -> zip((1, 4), (2, 5), (3, 6))
建立在缺口上回答。。。
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("
")
bar(1, a=2, b=3)
print("
")
three_params(1, 2, 3, 4, s=5)
输出:
1
(2, 3, 4, 5)
1
{ a : 2, b : 3}
1
(2, 3, 4)
{ s : 5}
基本上,任何数量的位置参数都可以使用*args,任何命名参数
除了函数调用之外,*args和**kwargs在类层次结构中也很有用,还可以避免在Python中编写__init__
方法。类似的用法可以在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])
子类可以是
class RetailItem(Item):
_expected_attributes = Item._expected_attributes + [ name , price , category , country_of_origin ]
class FoodItem(RetailItem):
_expected_attributes = RetailItem._expected_attributes + [ expiry_date ]
然后将子类实例化为
food_item = FoodItem(name = Jam ,
price = 12.0,
category = Foods ,
country_of_origin = US ,
expiry_date = datetime.datetime.now())
Also, a subclass with a new attribute which makes sense only to that subclass instance can call the Base class __init__
to offload the attributes setting.
This is done through *args and **kwargs. kwargs mainly used so that code is readable using named arguments. 例如
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)
可以设置为
usb_key = ElectronicAccessories(name = Sandisk ,
price = $6.00 ,
category = Electronics ,
country_of_origin = CN ,
specifications = 4GB USB 2.0/USB 3.0 )
完整的代码是此处
给定一个有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
想象一下这个玩具有一个三角形、圆形和矩形的袋子。那个包不能直接放进去。你需要打开袋子才能拿下这三件物品,现在它们已经装好了。Python*操作符完成这个解包过程。
*args
和**kwargs
:允许您向函数传递可变数量的参数。
*args
:用于向函数发送一个无关键字的可变长度参数列表:
def args(normal_arg, *argv):
print("normal argument:", normal_arg)
for arg in argv:
print("Argument in list of arguments from *argv:", arg)
args( animals , fish , duck , bird )
将产生:
normal argument: animals
Argument in list of arguments from *argv: fish
Argument in list of arguments from *argv: duck
Argument in list of arguments from *argv: bird
**kwargs*
**kwargs
允许您向函数传递带有关键字的可变长度参数。如果要处理函数中的命名参数,则应使用**kwargs
。
def who(**kwargs):
if kwargs is not None:
for key, value in kwargs.items():
print("Your %s is %s." % (key, value))
who(name="Nikola", last_name="Tesla", birthday="7.10.1856", birthplace="Croatia")
将产生:
Your name is Nikola.
Your last_name is Tesla.
Your birthday is 7.10.1856.
Your birthplace is Croatia.
在函数中同时使用这两种方法的一个很好的例子是:
>>> def foo(*arg,**kwargs):
... print arg
... print kwargs
>>>
>>> a = (1, 2, 3)
>>> b = { aa : 11, bb : 22}
>>>
>>>
>>> foo(*a,**b)
(1, 2, 3)
{ aa : 11, bb : 22}
>>>
>>>
>>> foo(a,**b)
((1, 2, 3),)
{ aa : 11, bb : 22}
>>>
>>>
>>> foo(a,b)
((1, 2, 3), { aa : 11, bb : 22})
{}
>>>
>>>
>>> foo(a,*b)
((1, 2, 3), aa , bb )
{}
这个例子将帮助您一次记住Python中的*args
、**kwargs
甚至super
和继承。
class base(object):
def __init__(self, base_param):
self.base_param = base_param
class child1(base): # inherited from base class
def __init__(self, child_param, *args) # *args for non-keyword args
self.child_param = child_param
super(child1, self).__init__(*args) # call __init__ of the base class and initialize it with a NON-KEYWORD arg
class child2(base):
def __init__(self, child_param, **kwargs):
self.child_param = child_param
super(child2, self).__init__(**kwargs) # call __init__ of the base class and initialize it with a KEYWORD arg
c1 = child1(1,0)
c2 = child2(1,base_param=0)
print c1.base_param # 0
print c1.child_param # 1
print c2.base_param # 0
print c2.child_param # 1
**
除了这个线索中的答案之外,这里还有另一个其他地方没有提到的细节。这扩展了Brad Solomon回答
使用python<code>str.format</code>时,使用<code>**
这在某种程度上类似于您可以使用pythonf-strings
f-string,但增加了声明一个dict来保存变量的开销(f-string不需要dict)。
## init vars
ddvars = dict()
ddcalc = dict()
pass
ddvars[ fname ] = Huomer
ddvars[ lname ] = Huimpson
ddvars[ motto ] = I love donuts!
ddvars[ age ] = 33
pass
ddcalc[ ydiff ] = 5
ddcalc[ ycalc ] = ddvars[ age ] + ddcalc[ ydiff ]
pass
vdemo = []
## ********************
## single unpack supported in py 2.7
vdemo.append(
Hello {fname} {lname}!
Today you are {age} years old!
We love your motto "{motto}" and we agree with you!
.format(**ddvars))
pass
## ********************
## multiple unpack supported in py 3.x
vdemo.append(
Hello {fname} {lname}!
In {ydiff} years you will be {ycalc} years old!
.format(**ddvars,**ddcalc))
pass
## ********************
print(vdemo[-1])
*args(或*any)表示每个参数
def any_param(*param):
pass
any_param(1)
any_param(1,1)
any_param(1,1,1)
any_param(1,...)
注意:不能将参数传递给*args
def any_param(*param):
pass
any_param() # will work correct
*参数在类型元组中
def any_param(*param):
return type(param)
any_param(1) #tuple
any_param() # tuple
对于访问元素,请不要使用*
def any(*param):
param[0] # correct
def any(*param):
*param[0] # incorrect
**千瓦时
**kwd or **any This is a dict type
def func(**any):
return type(any) # dict
def func(**any):
return any
func(width="10",height="20") # {width="10",height="20")
*args
是一个特殊参数,可以将0个或多个(位置)参数作为元组。
**kwargs
是一个特殊参数,可以将0个或多个(关键字)参数作为字典。
*在Python中,有两种参数位置参数和关键字参数:
*args
:例如,*args
可以将0个或多个参数作为元组,如下所示:
↓
def test(*args):
print(args)
test() # Here
test(1, 2, 3, 4) # Here
test((1, 2, 3, 4)) # Here
test(*(1, 2, 3, 4)) # Here
输出:
()
(1, 2, 3, 4)
((1, 2, 3, 4),)
(1, 2, 3, 4)
并且,当打印<code>*args</code>时,将打印4个不带括号和逗号的数字:
def test(*args):
print(*args) # Here
test(1, 2, 3, 4)
输出:
1 2 3 4
并且,参数
具有元组类型:
def test(*args):
print(type(args)) # Here
test(1, 2, 3, 4)
输出:
<class tuple >
但是,*args
没有类型:
def test(*args):
print(type(*args)) # Here
test(1, 2, 3, 4)
输出(错误):
TypeError:type()接受1或3个参数
并且,正常参数可以放在*args
之前,如下所示:
↓ ↓
def test(num1, num2, *args):
print(num1, num2, args)
test(1, 2, 3, 4)
输出:
1 2 (3, 4)
但是,**kwargs
不能放在*args
之前,如下所示:
↓
def test(**kwargs, *args):
print(kwargs, args)
test(num1=1, num2=2, 3, 4)
输出(错误):
SyntaxError:无效语法
并且,正常参数不能放在*args
之后,如下所示:
↓ ↓
def test(*args, num1, num2):
print(args, num1, num2)
test(1, 2, 3, 4)
输出(错误):
TypeError:test()缺少2个仅限关键字的必需参数:num1和num2
但是,如果正常参数具有默认值,则可以将它们放在*args
之后,如下所示:
↓ ↓
def test(*args, num1=100, num2=None):
print(args, num1, num2)
test(1, 2, num1=3, num2=4)
输出:
(1, 2) 3 4
此外,**kwargs
可以放在*args
之后,如下所示:
↓
def test(*args, **kwargs):
print(args, kwargs)
test(1, 2, num1=3, num2=4)
输出:
(1, 2) { num1 : 3, num2 : 4}
**kwargs
:例如,**kwargs
可以将0个或多个参数作为字典,如下所示:
↓
def test(**kwargs):
print(kwargs)
test() # Here
test(name="John", age=27) # Here
test(**{"name": "John", "age": 27}) # Here
输出:
{}
{ name : John , age : 27}
{ name : John , age : 27}
并且,当打印*kwargs
时,将打印2个键:
def test(**kwargs):
print(*kwargs) # Here
test(name="John", age=27)
输出:
name age
并且,kwargs
具有dict类型:
def test(**kwargs):
print(type(kwargs)) # Here
test(name="John", age=27)
输出:
<class dict >
但是,*kwargs
和**kwargs
没有类型:
def test(**kwargs):
print(type(*kwargs)) # Here
test(name="John", age=27)
def test(**kwargs):
print(type(**kwargs)) # Here
test(name="John", age=27)
输出(错误):
TypeError:type()接受1或3个参数
并且,正常参数可以放在**kwargs
之前,如下所示:
↓ ↓
def test(num1, num2, **kwargs):
print(num1, num2, kwargs)
test(1, 2, name="John", age=27)
输出:
1 2 { name : John , age : 27}
此外,*args
可以放在**kwargs
之前,如下所示:
↓
def test(*args, **kwargs):
print(args, kwargs)
test(1, 2, name="John", age=27)
输出:
(1, 2) { name : John , age : 27}
并且,正常参数和*args
不能放在**kwargs
之后,如下所示:
↓ ↓
def test(**kwargs, num1, num2):
print(kwargs, num1, num2)
test(name="John", age=27, 1, 2)
↓
def test(**kwargs, *args):
print(kwargs, args)
test(name="John", age=27, 1, 2)
输出(错误):
SyntaxError:无效语法
*args
and **kwargs
:实际上,您可以为*args
和**kwargs
使用其他名称,如下所示*args
和**kwargs
按惯例使用:
↓ ↓
def test(*banana, **orange):
print(banana, orange)
test(1, 2, num1=3, num2=4)
输出:
(1, 2) { num1 : 3, num2 : 4}
def foo(param1, *param2):
is a method can accept arbitrary number of values for *param2
,def bar(param1, **param2):
is a method can accept arbitrary number of values with keys for *param2
param1
is a simple parameter.例如,在Java中实现varargs的语法如下:
accessModifier methodName(datatype… arg) {
// method body
}
*args
和**kwargs
只是向函数输入无限字符的一种方式,如:
def print_all(*args, **kwargs):
print(args) # print any number of arguments like: "print_all("foo", "bar")"
print(kwargs.get("to_print")) # print the value of the keyworded argument "to_print"
# example:
print_all("Hello", "World", to_print="!")
# will print:
"""
( Hello , World )
!
"""
def foo(x, y, *args):
pass
def bar(x, y, **kwargs):
pass
*args
据我所知,*args
是一个由逗号、
分隔的参数数组,所以如果你想在上面foo
,它看起来像
foo("x","y",1,2,3,4,5)
所以如果你跑步
for a in args:
print(a)
它将按放置顺序打印参数,如1,2,3。。。
尽管这很容易实现和使用,但参数的顺序在这里很重要。因此,如果第一个参数应该是字符串,第二个参数是整数,如果调用方打乱了顺序,函数就会失败。
**kwargs
这些是关键字
参数,它们是一组命名参数,作为键/值对
或字典
传递,用分隔,
如果是多个。因此,对于栏
,您可以发送
bar("x", "y", name="vinod",address="bangalore",country="india")
并且可以在函数中单独读取
Name = kwargs[ name ]
Address = kwargs[ address ]
读取
kwargs
不需要在循环上枚举,参数的顺序也无关紧要。
最简单的解释是,*是传递元组的*args,**是传递字典的**kwargs。这些只是默认的通用名称。