Python中使用关键字传递位置参数后,如何向*args传递参数
Ah, I see the issue here! When you use keyword arguments for a and b, you can't just pass aa=(4,5,6) and expect it to go into the *aa parameter. That's because *aa is meant to catch extra positional arguments, not a keyword argument named aa—that would end up in **bb instead. Let me break this down and show you the right way to do it.
Why Your Current Call Isn't Working
Let's take your example call:
fun(b=1,a=2,aa=(4,5,6),dd=4,pp=5)
In this case, aa=(4,5,6) is treated as a keyword argument, so it gets added to the **bb dictionary. If you run this, you'll see output like:
2 1 () {'aa': (4, 5, 6), 'dd': 4, 'pp': 5}
Notice how aa is empty, and bb now has an entry for 'aa'? That's not what you want.
The Fix: Use the * Operator to Unpack Your Iterable
To get those values into *aa, you need to unpack your tuple or list using the * operator when calling the function. This tells Python to treat each element in the iterable as a separate positional argument, which *aa will then collect.
Here are two valid ways to do this:
Unpack a Tuple
fun(b=1,a=2,*(4,5,6),dd=4,pp=5)
Unpack a List
fun(b=1,a=2,*[4,5,6],dd=4,pp=5)
Either way, when you run the function, you'll get the output you're expecting:
2 1 (4, 5, 6) {'dd': 4, 'pp': 5}
Now *aa correctly holds the (4,5,6) tuple, and **bb only has the dd and pp key-value pairs.
Quick Recap
*aacollects extra positional arguments, not keyword arguments with the name 'aa'.- To pass a group of values to
*aawhen using keyword args for other parameters, use*to unpack your iterable into individual positional args.
内容的提问来源于stack exchange,提问作者user2779311

