raylee2015 发表于2年前

• 发表于 2年前
• 阅读 1
• 收藏 0
• 评论 0

1.位置：从左到右进行匹配

``````>>> def test(a,b,c):
print(a,b,c)

>>> a=1
>>> b=2
>>> c=3
>>> test(a,b,c)
1 2 3
>>>``````

2.关键字参数：通过参数名进行匹配

``````>>> def test(a,b,c):
print(a,b,c)

>>> a=1
>>> b=2
>>> c=3
>>> test(a,b,c)
1 2 3
>>> test(c=3,b=2,a=1)
1 2 3
>>>``````

3.默认参数：为没有传入值的参数定义参数值

``````>>> a=1
>>> b=2
>>> c=3
>>> def test(a,b=3,c=4):
print(a,b,c)

>>> test(a)
1 3 4
>>>``````

4.可变参数：收集任意多基于位置或者关键字的参数

``````>>> def test(*args):
print(args)

>>> a=1
>>> b=2
>>> test(a,b)
(1, 2)
>>> a=(1,2,3)
>>> b=[1,2,3]
>>> c='abc'
>>> d=5
>>> test(a,b,c,d)
((1, 2, 3), [1, 2, 3], 'abc', 5)
>>>``````

5.可变参数解包：传递任意多基于位置或者关键字的参数

``````>>> def test(**args):
print(args)

>>> test(1,2)
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
test(1,2)
TypeError: test() takes 0 positional arguments but 2 were given
>>> test(a=1,b=2)
{'a': 1, 'b': 2}
>>>``````

6.keyword-only模式

``````>>> def test(a,*args,b):
print(a,args,b)

>>> test(a=1,b=2)
1 () 2
>>> test(1,5,b=2)
1 (5,) 2``````

``````>>> def test(a,*args,b):
print(a,args,b)

>>> test(a=1,b=2)
1 () 2
>>> test(1,5,b=2)
1 (5,) 2
>>> test(1,5)
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
test(1,5)
TypeError: test() missing 1 required keyword-only argument: 'b'
>>> test(a=1,2)
SyntaxError: non-keyword arg after keyword arg
>>>``````

------------------------------------------------------------------

×