Python中,(*)会把接收到的参数形成一个元组,而(**)则会把接收到的参数存入一个字典
我们可以看到,foo方法可以接收任意长度的参数,并把它们存入一个元组中
1 2 3 4 5 6 7 8 9 10 11 12 |
|
(**)将接收到的参数存入一个字典
1 2 3 4 5 6 7 8 |
|
(*)和(**)一起使用
1 2 3 4 5 6 7 8 9 10 11 |
|
name作为foo第一个参数,在调用foo("hello", 1, 2, 3, middle="world", a=1, b=2, c=3)方法时,自然而然捕获了hello,而middle必须经过指定关键字参数才可以捕获值,否则会和之前的参数一样形成一个元组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
此外,我们还可以定义一个字典my_foo,并以foo(**my_foo)这样的方式,让name和middle各自捕获自己的值,没有捕获的则存入一个字典
当我们删除my_foo中的name,再像之前传入函数,函数会报错说需要name这个参数
1 2 3 4 5 |
|