Translation Notice
This article was machine-translated using DeepSeek-R1.
- Original Version: Authored in Chinese by myself
- Accuracy Advisory: Potential discrepancies may exist between translations
- Precedence: The Chinese text shall prevail in case of ambiguity
- Feedback: Technical suggestions regarding translation quality are welcomed
I. *[parameter name]
Calling
Valid Calls
Regular Call
*parameter name
is usually written as *args
, e.g.:
|
|
Try calling func
:
|
|
Thus, we observe that such functions can accept any number of arguments (including 0). *
packs the arguments into a tuple
, such as (1,)
, ()
, (1, 2, 3)
, ({}, set(), '', 0)
.
Special Call
If there’s already a tuple
object to pass as args
:
First define a tuple
object:
|
|
Wrong Approach
Common mistake:
|
|
((1, 2, 3),)? Shouldn’t it be (1, 2, 3)?
The system treats it as a single argument in args
, resulting in a “tuple within tuple” scenario. OH NO!
Correct Approach
Add *
before tuple_object
:
|
|
This is called “unpacking”.
Invalid Calls
Trying func(a=1, b=2)
:
|
|
Triggers TypeError
:
|
|
What’s a keyword argument
?
keyword argument
refers to parameter passing inname=value
format.- Simply put,
keyword argument
means passing parameters asname=value
pairs.
Thus, only positional arguments
(value-only format) should be used here.
Default Parameters
Parameters with *[parameter name]
cannot have default values:
As shown, setting default parameters causes SyntaxError
. To simulate default values:
|
|
Now it has default behavior:
|
|
Summary
*[parameter name]
indicates usingpositional arguments
, accepts any number of arguments, packs them into atuple
.- Special call:
*[tuple object]
- Cannot set default parameters directly; requires manual default handling.
II. **[parameter name]
Calling
Valid Calls
Regular Call
**parameter name
is usually written as **kwargs
, e.g.:
|
|
Calling func
requires name=value
format (hence kwargs
):
|
|
Such functions accept any number of keyword arguments
(including 0), packing them into a dict
, such as {'a': 1, 'b': 2, 'c': 3, 'd': 4}
, {'_tuple_obj': (), '_set_obj': set(), '_dict_obj': {}}
, {}
.
Special Call
If there’s a dict
object to pass as kwargs
:
Define the object:
|
|
Then:
|
|
Invalid Calls
Passing positional arguments
:
|
|
Triggers TypeError
:
|
|
Only keyword arguments
are allowed here.
Default Parameters
Similar to *args
, use manual default handling:
|
|
Now it has default behavior:
|
|
Summary
**[parameter name]
indicates usingkeyword arguments
, accepts any number ofname=value
pairs, packs them into adict
.- Special call:
**[dict object]
- Cannot set default parameters directly; requires manual default handling.