Python函数的其他特性
位置形参名和关键字形参名冲突
如果位置参数和关键字参数名发生冲突,当调用这个函数时会出错
def foo(name, **kwds):
return 'name' in kwds
print(foo(1, **{'name':2}))
输出:
E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/02.py
Traceback (most recent call last):
File "E:/Python3/Exercise/venv/02.py", line 8, in <module>
print(foo(1, **{'name':2}))
TypeError: foo() got multiple values for argument 'name'
Process finished with exit code 1
解决办法是,通过特殊参数/来限制位置参数
def foo(name, /, **kwds):
print(name)
return 'name' in kwds
print(foo(1, **{'name':2}))
输出:
E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/02.py
1
True
Process finished with exit code 0