Python中*参数和**参数的区别
时间: 2023-10-21 07:17:05 浏览: 122
在Python中,*参数和**参数都是用来传递可变数量的参数的。但是它们的用法和效果不同。
*参数
*参数用来传递可变数量的位置参数,它会将所有传递进来的位置参数打包成一个元组(tuple)。在函数调用时,可以使用*操作符将元组中的元素拆分开,作为位置参数传递给函数。
示例:
```
def my_func(*args):
print(args)
my_func(1, 2, 3) # 打印出 (1, 2, 3)
```
**参数
**参数用来传递可变数量的关键字参数,它会将所有传递进来的关键字参数打包成一个字典(dictionary)。在函数调用时,可以使用**操作符将字典中的元素拆分开,作为关键字参数传递给函数。
示例:
```
def my_func(**kwargs):
print(kwargs)
my_func(a=1, b=2) # 打印出 {'a': 1, 'b': 2}
```
需要注意的是,在函数定义时,*参数和**参数必须放在所有位置参数和关键字参数的后面。如:
```
def my_func(a, b, *args, **kwargs):
print(a, b, args, kwargs)
```
阅读全文
相关推荐


















