OS: Windows
Python: 3.8.8
IDE: Sublime Text 3
Location parameters and default parameters
Define a function, which contains two parameters. param1 is the location parameter that must be provided when calling the function. param2 is the default parameter. The default value is None (of course, it can be set to other values; note: try to point to the invariant object when defining the default parameter)
def demo_function1(param1, param2=None): """ Positional and default parameters of the function param1:Position parameter, which should be given when calling the function, otherwise it will be reported TypeError TypeError: * missing 1 required positional argument: * param2:Default parameters,This parameter may not be provided when calling the function,Current default None """ print(param1) print(param2)
Call demo_ The parameterparam1 of function1 is assigned "param1"
# Call demo_function1 only assigns a value to the position parameter param1 #Both assignment methods are OK #demo_function1(param1="param1") demo_function1("param1")
Output:
param1
None
Call demo_ The function1 parameter param2 is re assigned "param2"
demo_function1("param1", param2="param2") # demo_function1("param1", "param2")
Output:
param1
param2
Variable and keyword parameters
The variable parameters and keyword parameters of the defined function are theoretically the same as the above location parameters and keyword parameters, but the concept of parameters is abstracted
Define a function with variable parameters and keyword parameters:
def demo_function2(*args, **keywords): """ Variable and keyword parameters of functions *args : Variable parameters *keywords :Keyword parameters """ print(args, keywords)
*Args: * symbol defines that args is a variable parameter (Note: args is only a name, or it can be another name)
**Keywords: * * symbol defines that keywords is a keyword parameter (Note: keywords is only a name, and can also be other names)
Call demo_function2:
# args is 1, 2,"3" keywords is A="a",B="b" demo_function2(1, 2,"3", A="a",B="b")
Output:
(1, 2, '3') {'A': 'a', 'B': 'b'}
It can be seen that args is equivalent to a tuple; Keywords is a dict
Put the demo_ Function 2 can get each value of args and keywords by changing it; Modify demo_function2 :
def demo_function2(*args, **keywords): """ Variable and keyword parameters of functions *args : Variable parameters *keywords :Keyword parameters """ #print(args, keywords) for arg in args: print(arg) for keyword in keywords: print(keywords[keyword])
Call the modified demo again_ function2:
# args is 1, 2,"3" keywords is A="a",B="b" demo_function2(1, 2, "3", A="a", B="b")
Output:
1
2
3
a
b
The print part can be changed to the logic you want
You can also call the demo as follows_ The effect of function2 function is the same:
param_list = [1, 2, "3"] param_dict = {"A": "a", "B": "b"} #demo_function2(1, 2, "3", A="a", B="b") demo_function2(*param_list, **param_dict)Higher order function
map function
The map function receives two parameters: the first parameter is a function, and the second function is an iteratable object; The map function substitutes each element in the iteratable object into the first function and returns a new Iterator
First define a function as the parameter of the map function:
Function map_function: if param is str type, it will be converted to lowercase
def map_function(param): """Will parameter param Make lowercase""" if isinstance(param, str): param = param.lower() return param
Define a list as the second parameter of the map function:
demo_list = ["A", "B", "c", 1, 2, 3]
map function call:
result = map(map_function, demo_list)
Since the map function returns an Iterator lazy sequence, it can be converted from list to list
result = list(result)
Complete example:
def demo_function3(): """ map Function use """ demo_list = ["A", "B", "c", 1, 2, 3] result = map(map_function, demo_list) result = list(result) print(result) def map_function(param): """Will parameter param Make lowercase""" if isinstance(param, str): param = param.lower() return param
Call demo_function3 function:
Output:
['a', 'b', 'c', 1, 2, 3]
filter function
The filter function can be used to filter specific elements in a sequence
The usage is the same as the map function, and the syntax structure is the same
filter(filter_function, iterable_list)
Define a filter first_ function :
def filter_function(param): """If it is str Just return True""" return isinstance(param, str)
Then give an iterable_list :
iterable_list = [1, 2, 3, "A", "b", "C"]
Filter with the filter function and output the results:
result = list(filter(filter_function, iterable_list)) print(result)
Output:
['A', 'b', 'C']
The final result only retains the str type, and the int type is filtered out.
Complete example:
def filter_function(param): """If it is str Just return True""" return isinstance(param, str) def demo_function6(): iterable_list = [1, 2, 3, "A", "b", "C"] result = list(filter(filter_function, iterable_list)) print(result)
Call demo_function6 function, output:
['A', 'b', 'C']
Combine the map function and filter function to output the string in the list and convert it to lowercase:
def map_function(param): """Will parameter param Make lowercase""" if isinstance(param, str): param = param.lower() return param def demo_function6(): iterable_list = [1, 2, 3, "A", "b", "C"] result = list(filter(filter_function, map(map_function, iterable_list))) print(result)
Call demo_function6 function, output:
['a', 'b', 'c']
reduce function
The reduce function is similar to the map function. The first parameter is a function and the second function is an iteratable object. The difference is that the function of the first parameter of reduce needs to receive two parameters. The reduce function takes two elements from the iteratable object each time to calculate the result, and replaces the result with the next element of the iteratable object into the first parameter function
First define a function reduce_function is used as the first parameter of the reduce function:
def reduce_function(param_x, parax_y): """Return parameter product""" return param_x * parax_y
Call the reduce function:
"""reduce Function use""" from functools import reduce param_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = reduce(reduce_function, param_list) print(result)
Output:
3628800
Anonymous function lambdaLambda syntax structure: lambda parameters: logical expressions
For example:
lambda x: x + 1 #Equivalent to the following function # def f(x): # return x + 1 lambda x, y: x + y #Equivalent to the following function # def f(x, y): # return x + y
The element before the lambda colon represents the function parameters (multiple parameters are separated by commas); The expression after the colon represents the calculation logic and takes the operation result of the expression as the return value return
Return functionA function can also be used as the return value of a function, for example:
You can directly use lambda as the return value of the function return (or you can define your own function)
Define a demo_function5 function:
def demo_function5(): return lambda x, y: x + y
lambda is the return value of the function return
Then call demo_. function5 :
f = demo_function5() print(f) print(f.__name__) print(f(1, 2))
Output:
<function demo_function5.<locals>.<lambda> at ***>
<lambda>
3
You can see the demo_ The return value f of function5 is a function; The name of the function f is: lambda; Call f(x,y) to calculate the calculation result of x+y
Note: as the return value, the function must be called again before it can really call the returned function: the expression of lambda function will not be evaluated until f(1, 2) calls F
If there is a function now, if you don't want to change the existing function and want to add other functions when the function is executed, you can use the decorator at this time; First write a simple example:
demo_function7 function:
def demo_function7(): print("Here is demo_function7 function")
If you want to be in the demo_ If other functions are executed before function 7 is executed; First write a decorator function:
def wrapper_function(fn): """Decorator function""" def wrapper(*args, **keywords): print("Here is the decorator function output") return fn(*args, **keywords) return wrapper
Then modify the demo_function7 function:
@wrapper_function def demo_function7(): print("Here is demo_function7 function")
Only @ wrapper is added to the function definition_ function
Call demo_function7 output:
Here is the decorator function output
Here is the demo_function7 function
Call demo_ When the function7 function is used, it is equivalent to calling:
wrapper_function(demo_function7)()
If you want to be in the demo_ If some operations are performed before and after the function 7 is executed,
Modify wrapper_function:
def wrapper_function(fn): """Decorator function""" def wrapper(*args, **keywords): print("Here is demo_function7 Before function execution") func = fn(*args, **keywords) print("Here is demo_function7 After function execution") return func return wrapper
Call demo_function7 output:
Here is the demo_function7 before function execution
Here is the demo_function7 function
Here is the demo_ After the function7 function is executed
If wrapper_ If the function function needs to pass in parameters;
Modify wrapper_function:
def wrapper_function(param): """Decorator function""" def decorator(fn): def wrapper(*args, **keywords): print(f"This is wrapper_function Parameters:") print("Here is demo_function7 Before function execution") func = fn(*args, **keywords) print("Here is demo_function7 After function execution") return func return wrapper return decorator
Then modify the demo_function7 function:
@wrapper_function("param") def demo_function7(): print("Here is demo_function7 function")
"param" is passed to the wrapper_ Parameters of function
Call demo_function7 function output:
This is wrapper_ Parameter of function: param
Here is the demo_function7 before function execution
Here is the demo_function7 function
Here is the demo_ After the function7 function is executed
The demo is called_ Function7 function, which is equivalent to executing:
wrapper_function("param")(demo_function7)()
Next, if you call wrapper directly_ Function:
res = wrapper_function(demo_function7) print(type(res)) res = wrapper_function("param")(demo_function7) print(type(res))
output
<class 'function'>
The return value is a function type; Let's see what the function name is:
print(res.__name__)#Output function name
Output:
wrapper
This is because of wrapper_ The return value of function is wrapper function; So the decorator function is loaded__ name__ Property has been replaced with wrapper. In this way, some code execution that depends on function signature will make mistakes. Now we need to use functools.wraps to solve this problem;
Now modify the wrapper_function:
def wrapper_function(param): """Decorator function""" def decorator(fn): from functools import wraps @wraps(fn) def wrapper(*args, **keywords): print(f"This is wrapper_function Parameters:") print("Here is demo_function7 Before function execution") func = fn(*args, **keywords) print("Here is demo_function7 After function execution") return func return wrapper return decorator
In wrapper_ The wrapper function definition in the function function is added above
Wraps is a decorator, and wraps is a built-in tool in Python
Note that:
from functools import wraps
Call again:
res = wrapper_function("param")(demo_function7) print(res.__name__)#Output function name
Output:
demo_function7
Complete example with parameter decorator:
def wrapper_function(param): """Decorator function""" def decorator(fn): from functools import wraps @wraps(fn) def wrapper(*args, **keywords): print(f"This is wrapper_function Parameters:") print("Here is demo_function7 Before function execution") func = fn(*args, **keywords) print("Here is demo_function7 After function execution") return func return wrapper return decorator @wrapper_function("param") def demo_function7(): print("Here is demo_function7 function")
So far, the functions related to Python have come to an end temporarily;
If there are any mistakes, please comment and correct.