**(双星/星号)和*(星/星号)对参数有何作用?
-
09-06-2019 - |
题
在下面的方法定义中,什么是 *
和 **
做 param2
?
def foo(param1, *param2):
def bar(param1, **param2):
解决方案
这 *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
这 **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
这两种习惯用法都可以与普通参数混合,以允许一组固定参数和一些可变参数:
def foo(kind, *args, **kwargs):
pass
的另一种用法 *l
成语是 解压参数列表 调用函数时。
In [9]: def foo(bar, lee):
...: print bar, lee
...:
...:
In [10]: l = [1,2]
In [11]: foo(*l)
1 2
在Python 3中可以使用 *l
在作业的左侧(扩展可迭代拆包),尽管在这种情况下它给出的是列表而不是元组:
first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
Python 3 还添加了新的语义(请参阅 公众号 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
这样的函数只接受 3 个位置参数,以及后面的所有参数 *
只能作为关键字参数传递。
其他提示
还值得注意的是,您可以使用 *
和 **
调用函数时也是如此。这是一个快捷方式,允许您使用列表/元组或字典直接将多个参数传递给函数。例如,如果您有以下功能:
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'
单个 * 意味着可以有任意数量的额外位置参数。 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)
输出是
1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}
什么是
**
(双星)和*
(星号)执行参数
他们允许 要定义的函数接受 并为 用户通过 任意数量的参数,位置 (*
) 和关键字 (**
).
定义函数
*args
允许任意数量的可选位置参数(参数),这些参数将被分配给名为的元组 args
.
**kwargs
允许任意数量的可选关键字参数(参数),这些参数将位于名为的字典中 kwargs
.
您可以(并且应该)选择任何适当的名称,但如果目的是使参数具有非特定语义, args
和 kwargs
是标准名称。
扩展,传递任意数量的参数
您还可以使用 *args
和 **kwargs
分别从列表(或任何可迭代的)和字典(或任何映射)传入参数。
接收参数的函数不必知道它们正在被扩展。
例如,Python 2 的 xrange 没有明确期望 *args
, ,但由于它需要 3 个整数作为参数:
>>> x = xrange(3) # create our *args - an iterable of 3 integers
>>> xrange(*x) # expand here
xrange(0, 2, 2)
另一个例子,我们可以使用字典扩展 str.format
:
>>> foo = 'FOO'
>>> bar = 'BAR'
>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())
'this is foo, FOO and bar, BAR'
Python 3 中的新功能:定义仅包含关键字参数的函数
你可以有 仅关键字参数 之后 *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'})
还, *
可以单独使用来指示后面仅包含关键字参数,而不允许无限的位置参数。
def foo(arg, kwarg=None, *, kwarg2=None, **kwargs):
return arg, kwarg, kwarg2, kwargs
这里, kwarg2
Again 必须是显式命名的关键字参数:
>>> 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'
Python 2 兼容演示
*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))
我们可以查看函数签名的在线帮助, help(foo)
, ,这告诉我们
foo(a, b=10, *args, **kwargs)
让我们调用这个函数 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
我们还可以使用另一个函数来调用它,我们只需在其中提供 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())
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}
示例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
允许我们这样做,我们减少代码行,提高可读性和可维护性,并为程序中的逻辑拥有唯一的规范位置。如果我们需要更改此结构的任何部分,我们都有一个地方可以进行每项更改。
让我们首先了解什么是位置参数和关键字参数。下面是函数定义的示例 立场论据。
def test(a,b,c):
print(a)
print(b)
print(c)
test(1,2,3)
#output:
1
2
3
所以这是一个带有位置参数的函数定义。您也可以使用关键字/命名参数来调用它:
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
---------------------------------
现在我们知道带有位置参数和关键字参数的函数定义。
现在让我们研究“*”运算符和“**”运算符。
请注意,这些运算符可用于 2 个领域:
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.
所以记住
当“*”或“**”运算符用于 函数调用 -
“*”运算符将数据结构(例如列表或元组)解压缩为函数定义所需的参数。
'**' 运算符将字典解包为函数定义所需的参数。
现在让我们研究一下 '*' 运算符的使用 函数定义。例子:
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
功能中 定义 '**' 运算符将接收到的参数打包到字典中。
所以请记住:
在一个 函数调用 这 '*' 拆开包装 元组或列表的数据结构为由函数定义接收的位置或关键字参数。
在一个 函数调用 这 '**' 拆开包装 字典的数据结构转换为由函数定义接收的位置或关键字参数。
在一个 函数定义 这 '*' 包 将位置参数放入元组中。
在一个 函数定义 这 '**' 包 关键字参数放入字典中。
*
和 **
在函数参数列表中有特殊用途。 *
意味着参数是一个列表并且 **
这意味着该论点是词典。这允许函数进行任意数量的参数
虽然星型/平型运算符的用途已被 扩大 在 Python 3 中,我喜欢下表,因为它与这些运算符的使用相关 有功能. 。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) |
-----------------------------------------------------------------------
这实际上只是总结 Lorin Hochstein 的 回答 但我发现它很有帮助。
对于那些通过例子学习的人!
- 的目的
*
是让您能够定义一个函数,该函数可以采用以列表形式提供的任意数量的参数(例如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 = {}
# ----------------------------------------------------------------------
注意事项
**
专门为字典保留。- 首先发生非可选参数赋值。
- 不能两次使用非可选参数。
- 如果适用,
**
必须在之后*
, , 总是。
来自 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}
它还允许在单个函数调用中解压缩多个可迭代对象。
>>> range(*[1, 10], *[2])
range(1, 10, 2)
(感谢 mgilson 提供 PEP 链接。)
我想举一个别人没有提到的例子
* 还可以解压一个 发电机
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))
除了函数调用之外,*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])
然后子类可以是
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')
完整的代码是 这里
*
表示接收变量参数作为列表
**
意味着接收变量参数作为字典
使用如下:
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
在函数中使用两者的一个很好的例子是:
>>> 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')
{}
这个例子可以帮助你记住 *args
, **kwargs
乃至 super
以及 Python 中的继承。
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
长话短说
它将传递给函数的参数打包成 list
和 dict
分别在函数体内。当您定义这样的函数签名时:
def func(*args, **kwds):
# do stuff
可以使用任意数量的参数和关键字参数来调用它。非关键字参数被打包到一个名为的列表中 args
在函数体内,关键字参数被打包到一个名为的字典中 kwds
函数体内。
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
这是一个 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)
*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(param1, *param2):
是一个可以接受任意数量的值的方法*param2
,def bar(param1, **param2):
是一种可以接受任意数量的值的方法,其键为*param2
param1
是一个简单的参数。
例如,实现的语法 可变参数 在Java中如下:
accessModifier methodName(datatype… arg) {
// method body
}