不定参数
python中有两种常见的不定参数:
*args
: 用于传递不定数量的位置参数(Positional Arguments),这些参数将被收集到元组(Tuple)中**kwargs
: 用于传递不定数量的关键字参数(Keyword Arguments),这些参数将被收集到字典(Dictionary)中
def print_arguments_and_keywords(*args, **kwargs):
for arg in args:
print("Positional argument:", arg)
for key, value in kwargs.items():
print("Keyword argument:", key, value)
# 调用函数并传递位置参数和关键字参数
print_arguments_and_keywords('Hello', 'World', name='Alice', age=25)
输出为
('Positional argument:', 'Hello')
('Positional argument:', 'World')
('Keyword argument:', 'age', 25)
('Keyword argument:', 'name', 'Alice')
# 深入分析
*
和 **
在python中主要有三种用途:
- 拆分可迭代对象
- 可变变量的赋值
- 函数的可选参数标志
# 拆分可迭代对象
在 python
中,实现了 __iter__
函数的对象都是可迭代对象,如 tuple
、list
、dict
、set
、string
等。
拆分结果作为函数参数使用:
# 以下几行代码输出都是: a b c
print('a', 'b', 'c')
print(*('a', 'b', 'c'))
print(*['a', 'b', 'c'])
print(*{'a': 1, 'b': 2, 'c': 3})
print(*'abc')
拆分结果用于构建 tuple
、list
、dict
、set
等:
print([*'abc'])
print((*'abc'))
print((*'abc', 'd'))
# 可变变量的赋值
# list 的第一个元素赋值给 a,剩余元素赋值给 b
a, *b = [1, 2, 3]
print(a) # 输出为:1
print(b) # 输出为:[2, 3]
# list 的第一个元素赋值给 a,最后一个赋值给c,剩余元素赋值给 b
a, *b, c = [1, 2, 3, 4]
print(a) # 输出为:1
print(b) # 输出为:[2, 3]
print(c) # 输出为:4
# 函数的可选参数标志
函数的可选参数标志其实是前边两点的综合运用。
*args
的意义是将一个可迭代对象拆开,拆出的结果数量不定,用其表示函数的可变参数。
**kwargs
的意义是将一个字典拆开,拆出的结果数量不定,也用其表示函数的可变参数。
上次更新: 2023/12/08, 06:34:37