【 abstract 】
This is in addition to the data Structures section of the Automated Operations Workshop, which covers in detail some of the special Python techniques that can help you solve problems quickly when you’re writing code, so if you want to be a true Pythoner, To make your code more Pythonic, be sure to read this tutorial carefully!
**kwargs **kwargs **kwargs ** Kwargs ** Kwargs ** Kwargs
Python parameters can be divided into mandatory parameters (mandatory), default parameters (non-mandatory with default values), and variable parameters. These three parameters are applicable to different scenarios. The main difference lies in the mapping relationship between the actual parameters.
Parameter:
Argument:
This paper takes the implementation of a student’s personal situation function as an example.
[Required parameters]
In layman’s terms, a required parameter is a parameter that must be passed in. Define student() as follows:
def student(name, age) :
print("My name is ", name)
print("I am %s years old." % age)
Copy the code
We can see what happens to mandatory arguments by calling student()
student("ethan".18) My name is Ethan \n Iam 18 years old.
student(18."ethan") My name is 18 \n Iam Ethan years old.
Copy the code
- In general, the required parameters are passed in the order in which the function was defined, that is, mapped by position.
student(name="ethan", age=18) My name is Ethan \n Iam 18 years old.
student(age=18, name="ethan") My name is Ethan \n Iam 18 years old.
Copy the code
- If the names of all required parameters are specified, they can be passed in a different order, that is, mapping by name.
[Default parameters]
There is a new requirement to set the student’s age to 18 by default, i.e
- Don’t preach
age
When,age
Is the default value (18). - the
age
For 18,age
Is the incoming value.
Here, you use default arguments (also called keyword arguments, which are optional and have default values) in the form of = default after the parameter.
def student(name, age=18) :
print("My name is ", name)
print("I am %s years old." % age)
student("ethan") My name is Ethan \n Iam 18 years old.
student("ethan", age=20) My name is Ethan \n Iam 20 years old.
Copy the code
The above specifies that the default age parameter is 18.
We will discuss the specific characteristics of default parameters in the following two cases: when only default parameters are defined, and when both mandatory parameters and default parameters are defined.
1. Only default parameters are defined
def student(name="ethan", age=18) :
print("My name is ", name)
print("I am %s years old." % age)
student("ethan") My name is Ethan \n Iam 18 years old.
student(age=20, name="ethan") My name is Ethan \n Iam 18 years old.
Copy the code
1.1 When a function is called, the mapping rule for default parameters is similar to that for mandatory parameters, that is:
- In general, by position;
- Specify all name cases by name.
Second,When defining both mandatory and default parameters
2.1 Defining functions
def student(name, city="HZ", nation="CN", age) :
pass
SyntaxError: non-default argument follows default argument
Copy the code
When defining a function, mandatory parameters cannot be defined after default parameters.
2.2 When calling a function, define a student() function for discussion.
def student(name, age, city="HZ", nation="CN") : # name, age is mandatory, city, nation is default
print("My name is ", name)
print("I am %s years old." % age)
print("I am located at %s, %s" % (city, nation))
Copy the code
Among them:
name
.age
Is a mandatory parameter,city
.nation
Is the default parameter.
student("ethan", nation="SG".18, city="BJ") # SyntaxError: positional argument follows keyword argument
student("ethan", nation="SG", age=18, city="BJ") Name = Ethan age=18 city=BJ nation=SG
Copy the code
1. Generally, mandatory parameters must appear before default parameters; otherwise, the mapping relationship is unclear and an error occurs.
If a default parameter comes before a required parameter, is the first parameter passed with a default parameter or a required parameter without a default parameter?
student(name="ethan", nation="SG", age=18, city="BJ") Name = Ethan age=18 city=BJ nation=SG
Copy the code
2. If the names of all mandatory parameters are specified, the order in which the parameters are passed is ignored.
[Variable parameter]
Now there is a requirement to calculate a student’s total subject score, and the number of subjects varies, up to 3.
This requirement can be implemented by default parameters, set three default parameters, the default value is None, inside the function to determine whether the value is passed.
def student(name, age, subject_1=None, subject_2=None, subject_2=None) : # subject_* will be the exhausted subject score
sumScore = 0 # # total score
if (subject_1) {
sumScore += subject_1
}
if (subject_2) {
sumScore += subject_2
}
if (subject_3) {
sumScore += subject_3
}
print("My name is ", name)
print("My sum Score is " % sumScore)
Copy the code
- In the case of finite indeterminate parameters, the default parameters can be implemented, and the code is more redundant.
- However, if the number of undetermined parameters is not estimable, the default parameters cannot be implemented.
Therefore, to solve this problem, Python introduced mutable arguments (which are not mandatory and can be passed in a variable number). In previous articles we have occasionally used *args and **kwargs as function arguments, both of which are mutable arguments.
Mutable arguments make use of a syntactic feature in Python: packaging and unpacking
Package: Package multiple values into a tuple.
Unpack: Parsing a tuple or array into multiple values.
One, packaging and unpacking
Packing and unpacking is supported in many languages, but the syntax is slightly different. Here are a few examples of how to use packing and unpacking in Python.
scores = 80.90.98 # package syntax
chinese, math, english = val Unpack syntax
print(chinese, math, english) Output 80, 90, 98
chinese, math, english = scores # ValueError: not enough values to unpack (expected 4, got 3)
Copy the code
-
In other programming languages, there is no syntax for multiple variables to the left of an equal sign and only one variable to the right. This is a unique unpacking syntax in Python.
-
The number of elements in the unpacked sequence must be exactly the same as the number to the left of the assignment symbol =.
scores = 80.90.98.100 # package syntax
a, b = scores # ValueError: too many values to unpack (expected 2)
a, *b, c = scores # Package and unpackage syntax together using ?????????????????? Don't you want to explain the * here
print(b) # [90, 98]
print(c) # 4
Copy the code
- You can use the package syntax on the left side of the equal sign to package multiple values of the variable on the right side of the equal sign and assign them to variable B, which is a list-type variable.
scores = [80.90]
chinese, math = *scores # SyntaxError: can't use starred expression here
Copy the code
- The * operator should not be used on the right side of an expression. This is especially important. If you want to unpack, just use a, b = val.
def student(name, age, city, nation) :
print("My name is ", name)
print("I am %s years old." % age)
print("I am located at %s, %s" % (city, nation))
student(*["ethan".18."BJ"."CN"]) My name is Ethan \n Iam 18 years old. Iam located at HZ, CN.
student(*["ethan".18."BJ"]) # TypeError: student() missing 1 required positional argument: 'nation'
Copy the code
-
Unpacking can also be used to pass parameters to a function. In the above example, an array unpacking is passed to a function
a, b, c
Three parameters. -
The number of unpacked parameters must be the same as the number of parameters defined by the function.
If we don’t know how many parameters will be passed in, this is where args comes in
Second, * args
* Args is one of the variables in arguments because it does not specify a keyword but represents a combination of arguments.
The *args of the function definition can represent any number of parameters
def student(name, *scores) :
print("My name is ", name)
print("My scores are ", *scores)
print("My avg score is ".sum(scores))
student("ethan")
My name is Ethan
student("ethan".80)
My name is Ethan \n My scores are 80 \n My sum score is 80
student("ethan".80.90.98)
My name is Ethan \n My scores are 80 90 98 \n My sum score is 268
Copy the code
The following points can be observed from the above example:
-
*args
Multiple parameters can be packaged into a single tuple. -
*args
Is a variable parameter, can not pass, can pass as many as.
def student(*scores, name) :
print("My name is ", name)
print("My scores are ", *scores)
student(80.90."ethan") TypeError: foo() missing 1 Required keyword-only argument: 'a'
student(80.90, name="ethan") My name is Ethan \n My scores are 80 90
Copy the code
-
args
It’s just a common name, but you could call it anything, like in this casescores
. -
*args
Essentially, the remaining parameters are packed together when the function passes its arguments, so in the above example, no matter how many arguments we pass, it will be*args
Package, while the function definitionname
Parameters will never have a value, andname
It is not a variable parameter and is mandatory. Therefore, an error message will be reported -
Since mandatory parameters can be passed in by specifying parameter names, when a function is defined with mandatory parameters after mutable parameters, it must be called with a parameter name specified
You can imagine what would happen if you didn’t use *args? For example, the most commonly used print function in Python is defined as follows
def print(self, *args, sep=' ', end='\n', file=None) : # known special case of print
pass
print(1.2.3) Print 1, 2, 3
Copy the code
Print (1, 2, 3), or pass in any number of variables you want to print.
def print(self, args, sep=' ', end='\n', file=None) : # known special case of print
pass
print([1.2.3]) Print 1, 2, 3
Copy the code
Also to print any number of variables, we have to be combined into an array or a tuple incoming, the print of [1, 2, 3] example also force is acceptable, so if you want to print a lot of different types of variables, also need to these different types of variables of an array, it will make the code seem very strange, It doesn’t seem logical, and the code becomes less readable.
Third, * * kwargs
In essence, the * operation is to unpack the iterable. For lists and tuples, the * operation can be directly unpacked into elements. But dictionaries are also iterable, so what is the result of the * operation on dictionaries
def student(name, age) :
print("My name is ", name)
print("I am %s years old." % age)
student(*{"name": "ethan"."age": 18}) My name is name \n I am age years old.
student(*{"Name": "ethan"."Age": 18}) My name is name \n Iam Age years old.
Copy the code
As you can see from the output above, the * unpack operation seems to be only about the dictionary key to understand the package, so the above function call is actually equivalent to
fun(*["name"."age"])
fun(*["Name"."Age"])
Copy the code
So if you want to unpack both keys and values how do you do that?
** is used to unpack dictionaries in Python, as follows:
student(**{"name": "ethan"."age": 18}) My name is Ethan \n I am 18 years old.
Copy the code
- For dictionary unpacking, we must ensure that the dictionary keys and function definition parameter names are the same
** can be used to address elements of an iterable, but based on the underlying data structure of the dictionary, which is a two-dimensional array, addressing elements of a two-dimensional array requires two *.
Similarly, what if we can’t decide what keyword arguments to pass in when we define a function? You can then use the packaging syntax of keyword arguments when defining functions
def student(name, age, *scores, **kwargs) :
print("My name is ", name)
print("I am %s years old." % age)
print("My scores are ", *scores)
print("My avg score is ".sum(scores)/len(scores))
print("Other information:", kwargs)
student("ethan".18.80.90.98, gender="male", weight=70)
My name is Ethan I am 18 years old. My scores are 80 90 98 My AVG score is 89.333333333333 Other information: {'gender': 'male', 'weight': 70} '''
student("ethan".18.80.90.98, * * {"gender":"male"."weight":70}) Output same as above
Copy the code
-
*kwargs
This is also a convention, no special meaning, but it is best to use convention for readability. -
*args
Is to pack multiple parameters into tuples, and**kwargs
Is to package multiple keyword arguments into dictionaries.
【 summary 】
The general special techniques, while useful, have some extra caveats, so this article is obviously “dry,” but that’s what you have to go through to write more Pythonic code.
Finally, I leave a little question for you to think about, why not useprint(**kwargs)
To print the result of unpacking keyword arguments?
Welcome to add my personal public account [Python Playing automated Operation and Maintenance] to the reader exchange group, to get more dry content