下面这张图非常好的总结了python中函数各类参数的排列位置,我们总结一下,可以分成四个层级,从前往后分别是:
1.位置参数(Positional Arguments)
2.可选(含默认值)参数(Optional Arguments/Default Auguments)
3.不定长位置参数(Variable Optioncal Arguments)
4.不定长关键字参数(Varialbe Keyword Arguments)
我们可以通过inspect模块中的signature方法来查看函数中各个参数的类型
from inspect import signature
def f(a,b=2,*c,**d):
print(f'a:{a},b:{b},c:{c},d:{d}')
for name,val in signature(f).parameters.items():
print(name,val.kind)
输出的结果如下:
a POSITIONAL_OR_KEYWORD
b POSITIONAL_OR_KEYWORD
c VAR_POSITIONAL
d VAR_KEYWORD
我们在使用python函数的时候,经常会碰到报错(Trackback blabla)的情况,我们常见的有以下六类:
-SyntaxError: positional augument follows keyword argument
-SyntaxError: non-default argument follows default argument
-SyntaxError: keyword augument repeated
-TypeError: f() missing 1 required keyword-only argument: ‘b’,
-TypeError: f() missing 1 required positional augument:‘b’
-TypeError: f() got an unexpected keyword argument ‘a’
-TypeError: f() takes 0 positional arguments but 1 was given.
我们可以做成下面的脑图来方便记忆:
我们逐个来演示
一、missing required positional argument error
def f(a,b):
return a*b
print(f(1))
报错信息:
Traceback (most recent call last):
File "E:\python60days\funcParams\func_argument.py", line 24, in
print(f(1))
TypeError: f() missing 1 required positional argument: 'b'
二、more optional arguments are given error
def f(a):
return a*a
print(f(1,2))
报错信息:
Traceback (most recent call last):
File "E:\python60days\funcParams\func_argument.py", line 24, in
print(f(1,2))
TypeError: f() takes 1 positional argument but 2 were given
[Finished in 0.8s with exit code 1]
三、Postional Argument follows Keyword Argument
def f(a,b):
print(f'a:{a},b:{b}')
print(f(a=1,20))
报错信息:
File "E:\python60days\funcParams\func_argument.py", line 24
print(f(a=1,20))
^
SyntaxError: positional argument follows keyword argument
[Finished in 0.7s with exit code 1]
四、Repeated Arguments
def f(a,b):
print(f'a:{a},b:{b}')
print(f(a=1,a=2,b=3))
报错信息
File "E:\python60days\funcParams\func_argument.py", line 24
print(f(a=1,a=2,b=3))
^
SyntaxError: keyword argument repeated
[Finished in 0.9s with exit code 1]
五 non-default argument follows default argument
def f(a=1,b):
print(f'a:{a},b:{b}')
print(f(2,3))
报错信息:
File "E:\python60days\funcParams\func_argument.py", line 22
def f(a=1,b):
^
SyntaxError: non-default argument follows default argument
六、unexpected keyword argument ‘a’
def f(*a):
print(f'a:{a}')
f(a=1)
报错信息如下:
Traceback (most recent call last):
File "E:\python60days\funcParams\func_argument.py", line 24, in
f(a=1)
TypeError: f() got an unexpected keyword argument 'a'
七、positional arguments but was given
def f(**a):
print(a)
f(1)
报错信息:
Traceback (most recent call last):
File "E:\python60days\funcParams\func_argument.py", line 24, in
f(1)
TypeError: f() takes 0 positional arguments but 1 was given
也可以这样总结规则
一、前排的位置参数缺一不可、多一也不可能
二、关键词参数必须在位置参数右边
三、对同一个形参不能重复传值
四、非默认参数不能在默认参数之后
五、可变位置参数不能传入关键字参数
六、可变关键字参数不能传入位置参数