*args和**kwargs是什么意思?
def foo(x, y, *args):
def bar(x, y, **kwargs):
*args和**kwargs是什么意思?
def foo(x, y, *args):
def bar(x, y, **kwargs):
当前回答
在Python 3.5中,您还可以在列表、字典、元组和集合显示(有时也称为文字)中使用此语法。参见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提供PEP链接。)
其他回答
这个示例将帮助您立即记住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
*args是一个特殊的参数,可以将0个或多个(位置)参数作为元组。**kwargs是一个特殊的参数,可以将0个或多个(关键字)参数作为字典。
*在Python中,有两种参数位置参数和关键字参数:
*参数:
例如,*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)
并且,当打印*参数时,将打印4个数字,不带括号和逗号:
def test(*args):
print(*args) # Here
test(1, 2, 3, 4)
输出:
1 2 3 4
并且,args具有元组类型:
def test(*args):
print(type(args)) # Here
test(1, 2, 3, 4)
输出:
<class 'tuple'>
但是,*参数没有类型:
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)
输出(错误):
语法错误:无效语法
而且,正常参数不能放在*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可以使用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时,将打印两个键:
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)
输出(错误):
语法错误:无效语法
对于*args和**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}
*和**在函数参数列表中有特殊用法*表示参数是列表,**表示参数是一本字典。这允许函数接受任意数量的论据
给定一个有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
想象一下这个玩具有一个三角形、一个圆形和一个长方形的袋子。那个包不太合身。你需要打开袋子,取出这3件物品,现在它们就可以了。Python*运算符执行此解包过程。
对于那些通过实例学习的人!
*的目的是让您能够定义一个函数,该函数可以接受作为列表提供的任意数量的参数(例如f(*myList))。**的目的是通过提供字典(例如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 = {}
# ----------------------------------------------------------------------
注意事项
**专为词典保留。非可选参数赋值首先发生。不能两次使用非可选参数。如果适用,**必须始终在*之后。