python(第三天):Keyword-Only参数

时间:2021-02-03 23:21:44

1.这样的参数必须使用关键字语法来传递.

>>> def kownly(a,*b,c):
print(a,b,c)


>>> kownly(1,2,c=3)
1 (2,) 3
>>> kownly(a=1,c=3)
1 () 3
>>> kownly(1,2,3)
Traceback (most recent call last):
File "<pyshell#60>", line 1, in <module>
kownly(1,2,3)
TypeError: kownly() missing 1 required keyword-only argument: 'c'


 上面的代码中a可以使用位置和关键字来传递, c只能使用关键字进行传递.


2.使用*来表示一个函数不接受一个变量长度的参数, *后面的参数仍然使用关键字进行传递

>>> def kownly(a,*,b,c):
print(a,b,c)


>>> kownly(1,c=3,b=2)
1 2 3
>>> kownly(1,2,3)
Traceback (most recent call last):
File "<pyshell#67>", line 1, in <module>
kownly(1,2,3)
TypeError: kownly() takes 1 positional argument but 3 were given

3. 排序规则

keyword-only参数必须在*args之后,**args之前如下代码:

>>> def f(a,*b,**d,c=6):

SyntaxError: invalid syntax
>>> def f(a,*b,c=6,**d):
print(a,b,c,d)


>>> f(1,2,3,x=4,y=5)
1 (2, 3) 6 {'y': 5, 'x': 4}