*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文档中:
如果位置参数多于形式参数槽,则会引发TypeError异常,除非存在使用语法“*identifier”的形式参数;在这种情况下,该形参接收包含多余位置参数的元组(如果没有多余位置参数,则为空元组)。如果任何关键字参数与正式参数名称不对应,则会引发TypeError异常,除非存在使用语法“**标识符”的正式参数;在这种情况下,该形参接收包含多余关键字参数的字典(使用关键字作为关键字,将参数值作为对应值),如果没有多余关键字参数,则接收(新的)空字典。
其他回答
带*Args和**kwargs的“无限”Args
*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')
!
"""
*args和**kwargs是一种常见的习惯用法,允许任意数量的函数参数,如Python文档中关于定义函数的更多章节所述。
*参数将以元组的形式提供所有函数参数:
def foo(*args):
for a in args:
print(a)
foo(1)
# 1
foo(1,2,3)
# 1
# 2
# 3
**kwargs会给你所有关键字参数,但与作为字典的形式参数相对应的参数除外。
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个位置参数,*之后的所有参数只能作为关键字参数传递。
注:
语义上用于传递关键字参数的Python dict是任意排序的。然而,在Python 3.6中,关键字参数保证记住插入顺序。“**kwargs中元素的顺序现在对应于关键字参数传递给函数的顺序。”-Python3.6中的新功能事实上,CPython 3.6中的所有dict都将记住插入顺序作为实现细节,这在Python 3.7中成为标准。
除了函数调用之外,*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')
完整的代码在这里
TL;博士
以下是python编程中*和**的6种不同用例:
要使用*args:def foo(*args):pass接受任意数量的位置参数,这里foo接受任意数目的位置参数,即,以下调用是有效的foo(1)、foo(2,'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(2,'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
好处2:对同一个问题的回答也带来了一个新的视角,它分享了*和**在函数调用、函数签名、for循环等方面的含义。
TL;博士
它将传递给函数的参数分别打包到函数体中的list和dict中。当您这样定义函数签名时:
def func(*args, **kwds):
# do stuff
它可以用任意数量的参数和关键字参数调用。非关键字参数被打包到函数体内名为args的列表中,关键字参数被包装到函数体内称为kwds的dict中。
func("this", "is a list of", "non-keyowrd", "arguments", keyword="ligma", options=[1,2,3])
现在在函数体内部,当调用函数时,有两个局部变量,args是一个值为[“this”,“is a list of”,“non-keyword”,“arguments”]的列表,kwds是一个具有值为{“keyword”:“ligma”,“options”:[1,2]}的dict
这也反过来起作用,即从呼叫者一侧起。例如,如果函数定义为:
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)