Python variable parameters + keyword parameters

Python variable parameters + keyword parameters

The previous packing and unpacking are used here https://blog.csdn.net/qq_44994799/article/details/109681204

1. Definition

1.1. Variable parameters When
you see a *, a tuple is prepared by default, and the hash value 1, 2, 3 is assigned to *args, which is packaged and assembled into a tuple.
Insert picture description in this variable parameter
1.2. Keyword parameters When
you see two **, a dict is prepared by default. It is allowed to pass in 0 or any parameters with parameter names, which are automatically assembled into a dictionary inside the function. Role : the role of the extension function. The two parameters name and password are guaranteed, but if you are willing to provide more parameters, you can also receive them. For example, to do a user registration function, except that the user name and password are required, the others are optional. Using keyword parameters to define the function can meet the registration requirements.

Insert picture description here
1.3. Named keyword parameters: Restrict the name of keyword parameters. The parameter name must be passed in, otherwise an error will be reported.
Insert picture description here

2. Unpack and repack

When calling func (**dict1), ** represents unpacking
and when defining functions, **kwargs represents packaging, assembled into a dictionary

Insert picture description here

Insert picture description here
3. The order of parameter definition
Mandatory parameter-----> default parameter------> variable parameter------> named keyword parameter------> keyword parameter

Insert picture description here
Insert picture description here

Comprehensive example:

Important : f1(*args,**kw) # Here * and ** are all unpacked and unpacked. When it comes to the assignment in the function, * and ** represent the package, assembled into a tuple and a dictionary.
Insert picture description here

Insert picture description here
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44994799/article/details/109739400