table of Contents
Chapter VII, on the basis of the parameters of the function function
A, and parameter arguments
In parentheses defined parameter function definition stage, called formal parameters, referred to as formal parameters, in essence, is the variable name
def func(x, y):
print(x)
print(y)
Passed in the function call stage parentheses parameter, called the argument, in essence, is the value of the variable
func(1, 2)
Second, the location parameter
In the definition phase function according to the parameter defined sequentially from left to right, called the position parameter
Features : parameter defined according to the position, must be transmitted value, not a multiple (unless there is * args parameter or ** kwargs), nor a less
def func(x, y):
print(x)
print(y)
Calling the function stage according to the arguments left to right sequentially defined positions, called argument
Features : position according to parameter values corresponding to sequentially pass
func(1, 2)
Third, the key argument
When calling the function, according to the key: value of the form parameter passed to the specified value, called Keyword argument
Features : You can break the limit position, but can participate assigned to the specified shape
func(y=2, x=1)
Note :
You can mix position arguments and keyword arguments, but the location argument must be the keyword arguments left.
Position and can be mixed arguments keyword arguments, but can not repeat the assignment for a parameter.
func(x, y=2) func(y=2, x) # SyntaxError: positional argument follows keyword argument func(x, x=1) # NameError: name 'x' is not defined
Fourth, the default parameter
Definition phase, it has been assigned
Features : During the definition phase has already been assigned, which means you can not assign a value when calling.
def func(x, y=10):
print(x)
print(y)
func(2)
Note :
- Location parameter must be placed in the default parameter left.
- The default parameter values assigned only once in the definition phase, which means that the default value of the parameter in the function definition phase has been fixed.
m = 10
def foo(x=m):
print(x)
m = 111
foo() # 10
- The default value of the parameter should be immutable
def register(name, hobby):
hobby_list = []
hobby_list.append(hobby)
print(f"{name} prefer {hobby}'")
print(f"{name} prefer {hobby_list}")
register('nick', 'read')
def register(name, hobby, hobby_list=[]):
hobby_list.append(hobby)
print(f"{name} prefer {hobby}'")
print(f"{name} prefer {hobby_list}")
register('nick', 'read')
register('tank', 'zuipao')
register('jason', 'piao')
Description: a two-tier function effect is the same
to sum up
Application of arguments: depending on personal habits
application of formal parameters:
- In most cases the value of the same call, the parameters should be defined as a location parameter
- In most cases the value of the same call, you should define the parameters to the default parameter