python中结合使用位置实参和任意数量实参(收集参数)
1、如果要让函数接受不同类型的实参,必须在函数定义中将接受任意数量实参的形参放在最后。python先匹配位置参数和关键字参数,再将余下的实参都收集到最后一个形参中(收集参数)。
>>> def a(*x,y): ## 将收集参数放在所有形参的最前面
print(f"- {x}")
print(f"!{y}")
>>> a("aaa","bbb","ccc","ddd") ## 报错
Traceback (most recent call last):
File "<pyshell#232>", line 1, in <module>
a("aaa","bbb","ccc","ddd")
TypeError: a() missing 1 required keyword-only argument: 'y'
>>> def a(x,*y): ## 将收集参数放在后面
print(f"- {x}")
print(f"!{y}")
>>> a("aaa","bbb","ccc","ddd") ## 函数可以调用
- aaa
!('bbb', 'ccc', 'ddd')
>>> def a(x,*y):
print(f"- {x}")
for i in y:
print(f"!{i}")
>>>
>>> a("aaa","bbb","ccc","ddd") ## 函数可以调用
- aaa
!bbb
!ccc
!ddd