8. Functions
A function is a code block with a name that is used to accomplish specific work. def function definition, which indicates the function name. When defining a function, we determine the name and position of the parameter, and the interface definition of the function is completed. For the caller of the function, it is sufficient to know how to pass the correct arguments and what values the function will return , and the complex logic inside the function is encapsulated and the caller does not need to know.
To perform a specific task defined by a function, you call the function. When you perform the same task multiple times in a program, you do not have to write the code that completes the task repeatedly, just call the function that executes the task and let Python run the code in it.
Higher-order functions English called Higher-order function
8.1 Arguments and formal parameters
Formal parameters: A function of the information needed to complete its work.
Arguments: The information that is passed to the function when the function is called.
8.2 Passing parameters
A function definition may contain more than one parameter, so a function call may also contain more than one argument. There are many ways to pass arguments to a function, you can use positional arguments, which require the order of the arguments to be the same as the order of the formal parameters , or you can use the keyword argument, where each argument consists of a variable name and a value, and a list and a dictionary are used.
8.2.1 positional arguments
1. When you invoke a function, Python must associate each argument in a function call to a parameter in the function definition. Simple associations are based on the order of the arguments. This association is called a positional argument.
2. In the function, any number of positional arguments can be used as needed, and Python associates the arguments in the function call in order with the corresponding parameters in the function definition.
3. When you use positional arguments to invoke a function, the output will not be correct if the arguments are in the wrong order.
8.2.2 keyword arguments and keyword parameters
A keyword argument is a (name-value) pair that is passed to a function. You associate the name and value directly in the argument, so it is not confusing to pass an argument to the function. Keyword arguments let you not consider the order of arguments in a function call, but also clearly indicate the purpose of each value in a function call.
Describe_pet (animal_type= ' hamster ', pet_name= ' Harry ') |
You can pass in any number of keyword parameters:
>>> person (' Bob ', city= ' Beijing ') Name:bob age:35 Other: {' City ': ' Beijing '} >>> person (' Adam ', gender= ' M ', job= ' Engineer ') Name:adam age:45 Other: {' Gender ': ' M ', ' job ': ' Engineer '} |
8.2.3 Default Value
When you write a function, you can specify a default value for each parameter. When an argument is supplied to a parameter in the calling function, Python uses the specified argument value, otherwise the default value of the parameter is used. Therefore, when you specify a default value for a parameter, you can omit the corresponding argument from the function call. Using the default values simplifies function calls and clearly identifies typical uses of functions. The biggest benefit is the ability to reduce the difficulty of calling a function.
The default parameter must point to the immutable object!
def add_end (L=none): If L is None: L = [] L.append (' END ') Return L |
8.2.4 variable Parameters
When you define a mutable parameter and define a list or tuple parameter, you add an * number just before the parameter. Inside the function, the parameter numbers receives a tuple, so the function code is completely unchanged. However, when you call the function, you can pass in any parameter, including 0 parameters.
Def calc (*numbers): sum = 0 For N in numbers: sum = SUM + N * n return sum |
>>> Calc (1, 2) 5 >>> Calc () 0 |
Python allows you to add an * number to the list or tuple before the elements of a list or tuple into mutable parameters:
>>> nums = [1, 2, 3] >>> Calc (*nums) 14 |
*nums indicates that all elements of the list are nums as mutable parameters.
8.2.5 naming key parameters
For the keyword argument, the caller of the function can pass in any unrestricted keyword argument. As to exactly what is passed in, it needs to be checked inside the function via KW.
If you want to restrict the name of the keyword argument, you can use the named keyword argument, for example, to receive only city and job as the keyword parameter. The functions defined in this way are as follows:
def person (name, age, *, City, Job): Print (name, age, city, job) |
Unlike the keyword argument **kw, a named keyword parameter requires a special delimiter *,* the parameters that follow are treated as named keyword parameters.
If there is already a mutable parameter in the function definition, then the named keyword argument will no longer need a special delimiter *:
def person (name, age, *args, City, Job): Print (name, age, args, city, job) |
The named keyword argument must pass in the parameter name, which differs from the positional parameter. If the parameter name is not passed in, the call will error:
>>> person (' Jack ', ' Beijing ', ' Engineer ') Traceback (most recent): File "<stdin>", line 1, in <module> Typeerror:person () takes 2 positional arguments but 4 were given |
Because the call is missing the parameter name City and the Job,python interpreter treats all 4 parameters as positional parameters, the person () function accepts only 2 positional arguments.
A named keyword parameter can have a default value (the default), which simplifies the call:
def person (name, age, *, city= ' Beijing ', job): Print (name, age, city, job) |
Because the named keyword parameter city has a default value, the city parameter is not passed in when called:
>>> person (' Jack ', job= ' Engineer ') Jack Beijing Engineer |
Define a named keyword parameter do not forget to write the delimiter * If there is no mutable parameter, otherwise the definition will be the positional parameter.
8.2.5 equivalent function calls
The output is the same and the calling method is different.
Note: It doesn't matter which calling method to use, as long as the function call can generate the output you want. Use the calling method that is easiest for you to understand.
8.2.6 null function (pass)
If you want to define an empty function that does nothing, you can use the PASS statement:
Pass statement do nothing, pass can be used as a placeholder, such as now do not think how to write the code of the function, you can put a pass, so that the code can run up.
8.2.7 Avoid argument errors
No arguments are given, the arguments are in the wrong order, there is no attention to the argument format (quotation marks, etc.).
8.2.8 Global Statement (global variable)
If you want to modify a value stored in a global variable in a function, you must use the global statement for that variable.
8.3 return value
The function does not always display the output directly, instead it can process some data and return one or a set of values. The value returned by the function is called the return value. The return value of the function is returned with a return statement.
In a function, you can use the return statement to return a value to the line of code that called the function. The return value allows you to move most of your program's heavy work to the function, simplifying the main program.
8.3.1 return multiple values
The import Math statement imports the math package and allows subsequent code to reference the sin, cos, and other functions in the math package. You can return multiple values.
>>> x, y = Move (+, +, MATH.PI/6) >>> print (x, y) 151.96152422706632 70.0 |
But this is just an illusion, and the Python function returns a single value:
>>> r = Move (+, +, MATH.PI/6) >>> Print (R) (151.96152422706632, 70.0) |
The return value is a tuple! However, in syntax, the return of a tuple can omit parentheses, and multiple variables can receive a tuple at the same time, by the location of the corresponding value, so the Python function returns a multi-value is actually returned a tuple, but it is more convenient to write.
8.3.2 make an argument optional
Use the IF statement to determine if this argument is required.
8.3.3 Return Dictionary
Functions can return any type of value, including more complex data structures such as lists and dictionaries.
8.3.4 return function
Higher-order functions can also return a function as a result value, in addition to the ability to accept functions as parameters. If you do not need to sum immediately, you can return the SUM function without returning the result of the summation:
def lazy_sum (*args): def sum (): Ax = 0 For n in args: AX = ax + N return ax return sum |
When we call Lazy_sum (), we return the SUM function instead of summing the result:
>>> f = lazy_sum (1, 3, 5, 7, 9) >>> F <function Lazy_sum.<locals>.sum at 0x101c6ed90> |
The result of summing is actually computed when the function f is called:
Note: when we call Lazy_sum (), each call will return a new function, even if the same parameters are passed in:
>>> f1 = lazy_sum (1, 3, 5, 7, 9) >>> F2 = lazy_sum (1, 3, 5, 7, 9) >>> F1==F2 False |
The invocation results of F1 () and F2 () do not affect each other.
8.3.5 combined with functions and while
def get_formatted_name (first_name, last_name): "" Returns the neat name "" " Full_name = first_name + "+ last_name Return Full_name.title () While True: Print ("\nplease tell Me Your name:") Print ("(Enter ' Q ' at any time to quit)") F_name = input ("First Name:") if f_name = = ' Q ': Break L_name = input ("Last Name:") if l_name = = ' Q ': Break Formatted_name = Get_formatted_name (f_name, L_name) Print ("\nhello," + Formatted_name + "!") |
8.3.6 Closure Package
One thing to keep in mind when returning closures is that the return function does not refer to any loop variables, or to subsequent variables that change. If you must refer to a loop variable, you can create a function that binds the current value of the loop variable with its arguments, regardless of how the loop variable is subsequently changed, the value that has been bound to the function parameter is not changed, the disadvantage is that the code is longer, and the lambda function is used to shorten the code.
def count (): def f (j): def g (): Return j*j Return g FS = [] For I in range (1, 4): Fs.append (f (i)) # f (i) is executed immediately, so the current value of I is passed in F () Return FS >>> F1, F2, F3 = count () >>> F1 () 1 >>> F2 () 4 >>> F3 () 9 |
8.3.7 anonymous function lambda
When we pass in a function, there are times when we don't need to explicitly define a function, and it's easier to pass in an anonymous function directly.
In Python, there is a limited amount of support for anonymous functions. As an example of the map () function, when calculating f (x) =x2, in addition to defining an F (x) function, you can also pass in the anonymous function directly:
>>> list (map (lambda x:x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) [1, 4, 9, 16, 25, 36, 49, 64, 81] |
The comparison shows that the anonymous function lambda x:x * x is actually:
The keyword lambda represents an anonymous function, and the x preceding the colon represents the function parameter. There is a limit to the anonymous function, that is, there can be only one expression, without writing return, the return value is the result of that expression.
There is a benefit to using anonymous functions because the function does not have a name and does not have to worry about function name collisions. In addition, the anonymous function is also a function object, you can assign the anonymous function to a variable, and then use the variable to invoke the function:
>>> f = Lambda x:x * x >>> F <function <lambda> at 0x101c6ef28> >>> F (5) 25 |
8.4 Delivery List
For name in Names: you often find it useful to pass a list to a function, which may contain names, numbers, or more complex objects such as dictionaries. Once the list is passed to the function, the function can access its contents directly. The following function is used to improve the efficiency of the processing list.
8.4.1 Modifying a list in a function
1. Once the list is passed to the function, the function can modify it. Any changes you make to this list in a function are permanent, allowing you to handle large amounts of data efficiently.
2. Add or remove append POPs
3. A function completes a task, and functions can be called each other. Optimize functions for easy maintenance and modification.
8.4.2 Disable modification of functions
To solve this problem, you can pass a copy of the list to the function instead of the original, so that any modifications made by the function affect only the copy, without affecting the original.
Function_name (list_name[:]), [:] is equivalent to replication.
8.5 Passing any number of arguments (variable arguments)
Sometimes you don't know in advance how many arguments a function needs to accept, but it's good that Python allows a function to collect any number of arguments from the calling statement.
def Make_pizza (*toppings):
The asterisk in the parameter name *toppings lets python create an empty tuple named toppings and encapsulates all the received values into this tuple. The print statement in the body of the function proves that Python can handle situations where a function is called using a value, or that it uses three values to invoke a function, by generating output. It handles different calls in a similar way, noting that Python encapsulates the arguments into a tuple, even if the function receives only one value.
8.5.1 using positional arguments and variable arguments
If you want the function to accept different types of arguments, you must place the formal parameters that will accept any number of arguments in the function definition at the end. Python matches the positional arguments and the key arguments first, and then collects the remaining arguments into the last formal parameter.
8.5.2 using variable arguments and keyword arguments
Def build_profile (First, Last, **user_info):
The definition of function build_profile () requires a first and last name, while allowing the user to provide any number of name-value pairs as needed. Two asterisks in formal parameter **user_info Let python create an empty dictionary named User_info and encapsulate all the name-value pairs received into the dictionary. In this function, you can access the name-value pairs in User_info as you would access other dictionaries.
For key, value in User_info.items ():
Profile[key] = value
User_profile = Build_profile (' Albert ', ' Einstein ', location= ' Princeton ', field= ' physics ')
8.5.3 using parameter combinations
1. Define functions in Python, which can be combined using the required parameters, default parameters, variable parameters, keyword parameters, and named keyword parameters. Note, however, that the order of the parameter definitions must be: required, default, variable, named keyword, and keyword parameters.
The 2.python function has a very flexible parameter pattern, which allows for simple invocation as well as the introduction of very complex parameters.
3. The default parameter must be used immutable object, if it is a mutable object, the program will run with a logic error!
4. Be aware of the syntax for defining mutable parameters and keyword parameters:
5.*args is a variable parameter, and args receives a tuple;
6.**KW is the keyword parameter, and kw receives a dict.
7. And how to pass in the syntax for variable and keyword arguments when calling a function:
Variable parameters can be passed directly: Func (1, 2, 3), or the list or tuple can be assembled first, and then passed through *args: Func (* (1, 2, 3));
Keyword parameters can be directly passed in: Func (A=1, b=2), can be assembled dict, and then passed through **kw: func (**{' a ': 1, ' B ': 2}).
Using *args and **kw is a Python idiom, but it can also be used with other parameter names, but it's best to use idioms.
8.5.4 Recursive parameters
Inside a function, you can call other functions. If a function calls itself internally , the function is a recursive function. The advantage of recursive functions is that they are simple in definition and clear in logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion.
def fact (N): If n==1: Return 1 return n * Fact (N-1) |
The use of recursive functions requires careful prevention of stack overflow. In the computer, the function call is implemented through a stack (stack) of this data structure, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the size of the stack is not infinite, there are too many recursive calls that can cause the stack to overflow.
The movement of Hanoi can be implemented very simply with recursive functions.
8.6 Higher order functions
8.6.1 Higher order functions
Since the variable can point to a function, the function's arguments can receive the variable, then one function can receive another function as a parameter, which is called the higher order function.
def add (x, Y, f): return f (x) + f (Y) |
8.6.2 built-in functions
1. The absolute value of the function abs (), only one parameter.
2. Determine the object type, using the type () function:
>>> Type (123) <class ' int ' > >>> type (' str ') <class ' str ' > >>> type (None) <type (None) ' Nonetype ' > |
3. Calculate the square root can call the Math.sqrt () function.
4.lower () returns a lowercase string.
The 5.__len__ method returns the length. In Python, if you call the Len () function to try to get the length of an object, in fact, inside the Len () function, it automatically calls the __len__ () method of the object, so the following code is equivalent:
>>> len (' ABC ') 3 >>> ' ABC '. __len__ () 3 |
The 6.max function max () can receive any number of arguments and return the largest one.
7. If you want to get all the properties and methods of an object, you can use the Dir () function, which returns a list that contains a string, for example, to get all the properties and methods of a str object:
The 8.Python built-in hex () function converts an integer to a hexadecimal-represented string.
9. It is not convenient to use type () for the inheritance relationship of class. To determine the class type, we can use the isinstance () function. Parameter types are checked and only parameters of integer and floating-point type are allowed. Data type checking can be implemented with built-in function isinstance (). Use the built-in isinstance function to determine if a variable is a string.
10. With GetAttr (), SetAttr (), and hasattr (), we can manipulate the state of an object directly.
>>> hasattr (obj, ' x ') # have attribute ' x '? True >>> obj.x 9 >>> hasattr (obj, ' y ') # have attribute ' y '? False >>> setattr (obj, ' y ', 19) # Set a property ' Y ' >>> hasattr (obj, ' y ') # have attribute ' y '? True >>> getattr (obj, ' y ') # Get property ' Y ' 19 >>> obj.y # Get property ' Y ' 19 |
With the built-in series of functions, we can parse any Python object and get its internal data. It is important to note that we only get object information when we do not know the object information.
The map () and reduce () functions are built in 11.Python. Map functions The incoming function sequentially to each element of the sequence and returns the result as a new iterator.
>>> def f (x): ... return x * x ... >>> r = Map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> List (R) [1, 4, 9, 16, 25, 36, 49, 64, 81] |
Usage of reduce. Reduce functions a function in a sequence [X1, x2, x3, ...] , the function must receive two parameters, and reduce accumulates the result and the next element of the sequence.
>>> from functools Import reduce >>> def fn (x, y): ... return x * ten + y ... >>> reduce (FN, [1, 3, 5, 7, 9]) 13579 |
The 12.Python built-in filter () function is used for filtering sequences. Filter () also receives a function and a sequence . Unlike map (), filter () applies the incoming function to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is true or false. The key is to implement a "filter" function correctly. Notice that the filter () function returns a iterator, which is an inert sequence, so to force filter () to complete the result of the calculation, you need to use the list () function to get all the results and return to the list.
def is_odd (n): return n% 2 = = 1 List (filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15])) # results: [1, 5, 9, 15] |
The 13.Python built-in sorted () function allows you to sort the list.
>>> Sorted ([36, 5,-12, 9,-21]) [-21,-12, 5, 9, 36] |
The 14.sorted () function is also a high-order function, and it can also receive a key function to implement a custom sort, for example, by absolute size. To reverse sort, you can pass in the third parameter reverse=true without having to change the key function.
>>> sorted ([' Bob ', ' about ', ' Zoo ', ' credits '], Key=str.lower, reverse=true) [' Zoo ', ' credits ', ' Bob ', ' about '] |
The 15.Python built-in enumerate function can turn a list into an index-element pair so that both the index and the element itself can be iterated in the For loop.
The 16.round () function can return decimals of any bit.
8.6.3 Decorator
A way to dynamically add functionality during code runs, called an "adorner" (Decorator). Essentially, decorator is a higher-order function that returns a function. Adorner: Does not change the function itself, adding new functions.
The function object has a __name__ property that can get the name of the function:
>>> def now (): ... print (' 2015-3-25 ') ... >>> F = Now >>> F () 2015-3-25 >>> now.__name__ ' Now ' >>> f.__name__ ' Now ' |
Python's built-in @property decorator is responsible for turning a method into a property invocation:
Class Student (object): @property DEF score (self): Return Self._score @score. Setter DEF score (self, value): If not isinstance (value, int): Raise ValueError (' score must is an integer! ') If value < 0 or value > 100: Raise ValueError (' score must between 0 ~ 100! ') Self._score = value |
@property is widely used in the definition of a class, allowing the caller to write short code while guaranteeing the necessary checks on the parameters, thus reducing the likelihood of errors when the program runs.
@unique adorners can help us check that there are no duplicate values.
8.7 Storing functions in a module
To write maintainable code, you can group many functions into separate files so that each file contains relatively few code. In Python, a . py file is called a module.
One of the advantages of functions is that they can be used to separate blocks of code from the main program. By assigning a descriptive name to a function, the main program is much easier to understand. You can also go a step further by storing the function in a separate file called a module, and then importing the module into the main program. The import statement allows the code in the module to be used in the currently running program file.
By storing the function in a separate file, you can hide the details of the program code and focus on the high-level logic of the program. This also allows you to reuse functions in many different programs. After you store the functions in a separate file, you can share them with other programmers instead of the entire program. Knowing how to import a function also allows you to use libraries written by other programmers.
To avoid module name collisions, Python introduces a way to organize modules by directory, called packages. Once the package is introduced, all modules will not conflict with others as long as the package name in the top layer does not conflict with others. Now, the name of the abc.py module becomes MYCOMPANY.ABC, and similarly, the xyz.py module name becomes mycompany.xyz.
Note that each package directory will have a __init__.py file that must exist, otherwise Python will treat the directory as a normal directory instead of a package. __init__.py can be either an empty file or a Python code, because __init__.py itself is a module, and its module name is MyCompany.
8.7.1 Importing the entire module
To make a function import, you have to create the module first. A module is a file with a. py extension that contains the code that you want to import into your program.
If __name__== ' __main__ ': Test () |
The first step in using the module is to import the module, and when we run the Hello module file at the command line, the Python interpreter __name__ a special variable to __main__, and if the Hello module is imported elsewhere, the If judgment fails, so This if test allows a module to execute some extra code while running through the command line, most commonly running tests.
8.7.2 Scope
In a module, we may define many functions and variables, but some functions and variables we want to use for others, some functions and variables we want to use only within the module. In Python, this is done through the _ prefix. Normal functions and variable names are public and can be directly referenced, such as ABC,X123,PI, etc., variables such as __xxx__ are special variables that can be referenced directly, but have special uses, such as the above __author__,__name__ is a special variable, hello module definition of the document comments can also be accessed with special variable __doc__, our own variables are generally not used in this variable name; functions or variables like _xxx and __xxx are nonpublic (private) and should not be referenced directly, such as _abc,_ _ABC, etc.;
Private functions or variables should not be referenced by others, what is the use of them? Take a look at the example:
def _private_1 (name): Return ' Hello,%s '% name def _private_2 (name): Return ' Hi,%s '% name def greeting (name): If Len (name) > 3: return _private_1 (name) Else return _private_2 (name) |
We expose the greeting () function in the module and hide the internal logic with the private function, so that calling the greeting () function does not concern the internal private function details, which is also a very useful way to encapsulate and abstract the code. That is, functions that do not need to be referenced externally are all defined as private, and only functions that need to be referenced externally are defined as public.
8.7.3 Importing specific modules
Storing multiple functions in a module, separated by commas, allows you to import any number of functions from the module.
8.7.4 using as to assign aliases to functions
From pizza import Make_pizza as MP
If the name of the function to be imported may conflict with an existing name in the program, or if the name of the function is too long, you can specify a short and unique alias-another name for the function, similar to a nickname. To assign this special nickname to a function, you need to do so when you import it.
8.7.5 assigning aliases to modules using as
You can also assign aliases to modules. By assigning a short alias to the module (such as assigning the alias p to the module pizza), you can make it easier to invoke the functions in the module. Compared to Pizza.make_pizza (), P.make_pizza () is more concise.
8.7.6 use * To import all functions in the module
Use the asterisk (*) operator to allow Python to import all functions in the module.
However, it is best not to use this import method when using a large module that is not written by yourself: if the name of a function in the module is the same as the name used in your project, it can lead to unexpected results: Python may encounter multiple functions or variables with the same name, overwriting the function instead of importing all the functions separately.
8.8 Guidelines for writing functions
There are a few details to keep in mind when writing a function.
1. You should assign a descriptive name to the function and use only lowercase letters and underscores in it. Descriptive names can help you and others understand what the code wants to do. The above conventions should also be followed when naming modules.
2. Each function should contain a comment that briefly describes its functionality , which should be immediately followed by the function definition and in the form of a document string . A well-documented function allows other programmers to use it simply by reading the description in the document string: they can trust the code to run as described, and can use it in their own programs as long as they know the name of the function, the required arguments, and the type of the return value.
3. when specifying a default value for a parameter, do not have spaces on either side of the equal sign.