*args和**kwargs是什么意思?
def foo(x, y, *args):
def bar(x, y, **kwargs):
*args和**kwargs是什么意思?
def foo(x, y, *args):
def bar(x, y, **kwargs):
当前回答
此表便于在函数构造和函数调用中使用*和**:
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) |
-----------------------------------------------------------------------
这真的只是用来概括洛林·霍希斯坦的答案,但我觉得它很有用。
相关地:在Python 3中扩展了星形/splat运算符的用法
其他回答
除了函数调用之外,*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())
此外,具有仅对该子类实例有意义的新属性的子类可以调用基类__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)
其可以被初始化为
usb_key = ElectronicAccessories(name = 'Sandisk',
price = '$6.00',
category = 'Electronics',
country_of_origin = 'CN',
specifications = '4GB USB 2.0/USB 3.0')
完整的代码在这里
上下文
python 3.x使用打开包装**与字符串格式一起使用
与字符串格式一起使用
除了本主题中的答案之外,还有一个其他地方没有提到的细节。这扩展了Brad Solomon的答案
使用python str.format时,使用**解包也很有用。
这有点类似于使用python f-string 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])
对于那些通过实例学习的人!
*的目的是让您能够定义一个函数,该函数可以接受作为列表提供的任意数量的参数(例如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 = {}
# ----------------------------------------------------------------------
注意事项
**专为词典保留。非可选参数赋值首先发生。不能两次使用非可选参数。如果适用,**必须始终在*之后。
*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}
还值得注意的是,在调用函数时也可以使用*和**。这是一个快捷方式,允许您直接使用列表/元组或字典将多个参数传递给函数。例如,如果您具有以下功能:
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的参数完全相同。否则将抛出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'