python关键字参数和位置参数

时间:2023-12-23 21:34:49

关键字参数必须跟随在位置参数后面! 因为python函数在解析参数时, 是按照顺序来的, 位置参数是必须先满足, 才能考虑其他可变参数.,否则报错如下:

In [74]: print(s1.format(name='jenkins',"good","kg",a='python'))
File "<ipython-input-74-64057fd78193>", line 1
print(s1.format(name='jenkins',"good","kg",a='python'))
^
SyntaxError: positional argument follows keyword argument

场景:

In [79]: s1=('{name} is {}, he is 100{}, he love is {a}')

错误做法:

In [76]: print(s1.format(name='jenkins',a='python','good','kg'))
File "<ipython-input-76-25b0eb5fd5a0>", line 1
print(s1.format(name='jenkins',a='python','good','kg'))
^
SyntaxError: positional argument follows keyword argument

正确做法:

In [78]: print(s1.format("good","kg",a='python',name='jenins'))
jenins is good, he is 100kg, he love is python

意思就是说先写关键字,关键字写完之后,再写赋值,赋值跟在关键字之后