网友问题:
什么意思?*args
**kwargs
def foo(x, y, *args):
def bar(x, y, **kwargs):
网友回答:
还值得注意的是,您也可以在调用函数时使用 和。这是一个快捷方式,允许您使用列表/元组或字典直接将多个参数传递给函数。例如,如果您有以下函数:*
**
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'
网友回答:
and 是一种常见的习惯用法,允许对函数使用任意数量的参数,如 Python 文档中有关定义函数的更多信息部分所述。*args
**kwargs
这将给你所有函数参数作为一个元组:*args
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
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
**kwargs
网友回答:
The single * means that there can be any number of extra positional arguments. can be invoked like . In the body of foo() param2 is a sequence containing 2-5.foo()
foo(1,2,3,4,5)
The double ** means there can be any number of extra named parameters. can be invoked like . In the body of bar() param2 is a dictionary containing {‘a’:2, ‘b’:3 }bar()
bar(1, a=2, b=3)
With the following code:
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}
模板简介:该模板名称为【**(双星/星号)和*(星号/星号)对参数有什么作用?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。