(151.96152422706632, 70.0)
The return value is a tuple! However, syntactically, parentheses can be omitted when returning a tuple, and multiple variables can receive a tuple at the same time and assign corresponding values according to position. Therefore, Python's function returning multiple values actually returns a tuple, but it is more convenient to write. .
8.3.2 Make the actual parameter optional
Use the if statement to determine whether this actual parameter is needed.
8.3.3 Return Dictionary
The function can return any type of value, including more complex data structures such as lists and dictionaries.
8.3.4 Return function
In addition to accepting functions as parameters, higher-order functions can also return functions as result values. If you do not need to sum immediately, you can not return the summation result, but return the summation function:
##def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax Return sum
| When we call lazy_sum(), what is returned is not the summation result, but the summation function:
##>>> f = lazy_sum(1, 3, 5, 7, 9)
>>> f
.sum at 0x101c6ed90>
|
## When function f is called, the result of the sum is actually calculated:
##>>> f()
25
## | 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
# f1() and The calling results of f2() do not affect each other. |
8.3.5 Combine functions with while
##def get_formatted_name(first_name, last_name): ""Return 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 One thing to keep in mind when returning a closure is: the return function should not reference any loop variables, or variables that will change subsequently. If you must refer to a loop variable, the method is to create another function and use the parameters of the function to bind the current value of the loop variable. No matter how the loop variable changes subsequently, the value bound to the function parameter will not change. The disadvantage is that the code is longer. long, you can use lambda functions to shorten the code.
|
def count(): def f(j): def g(): i)) # f(i) is executed immediately, so the current value of i is passed into 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, sometimes there is no need to explicitly define the function. It is more convenient to pass in the anonymous function directly.
In Python, limited support is provided for anonymous functions. Still taking the map() function as an example, when calculating f(x)=x2, in addition to defining a function of f(x), you can also directly pass in an anonymous function:
>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[ 1, 4, 9, 16, 25, 36, 49, 64, 81]
| ## By comparison, it can be seen that the anonymous function lambda x: x * x In fact:
##def f(x):
return x * x
|
The keyword lambda represents an anonymous function, and the x before the colon represents function parameters. Anonymous functions have a limitation, that is, they can only have one expression. There is no need to write return. The return value is the result of the expression.
There is an advantage to using anonymous functions, because the function has no name, so you don’t have to worry about function name conflicts. In addition, the anonymous function is also a function object. You can also assign the anonymous function to a variable and then use the variable to call the function:
>>> ; f = lambda x: x * x
>>> f
5)
25
8.4 Passing a list
for name in names: You will often find it useful to pass a list to a function. This list may contain names, numbers, or more complex objects. (like a dictionary). Once a list is passed to a function, the function can directly access its contents. Use functions below to improve the efficiency of processing lists.
8.4.1 Modify the list in the function
1. After passing the list to the function, the function can modify it. Any modifications made to this list within the function are permanent, allowing you to process large amounts of data efficiently.
2. Add or delete append pop
3. A function completes a task, and functions can call each other. Optimize functions to facilitate maintenance and modification.
8.4.2 Forbidden to modify functions
To solve this problem, you can pass a copy of the list to the function instead of the original; in this way, any modifications made by the function will only affect the copy and not the original at all. Original.
Function_name(list_name[:]), [:] is equivalent to copying.
8.5 Pass any number of actual parameters (variable parameters)
Sometimes, you don’t know in advance how many actual parameters a function needs to accept. Fortunately, Python allows the function to collect any number of actual parameters from the calling statement. The number of arguments.
Def make_pizza(*toppings):
The asterisk in the parameter name *toppings tells Python to create an empty tuple named toppings and encapsulate all received values in in this tuple. The print statement inside the function body generates output to demonstrate that Python can handle calling the function with one value, as well as calling the function with three values. It handles different calls in a similar way. Note that Python encapsulates the arguments into a tuple, even if the function only receives a single value.
8.5.1 Combining positional arguments and variable arguments
If you want a function to accept different types of arguments, you must accept any number of formal parameters in the function definition. Put it last. Python first matches positional arguments and keyword arguments, 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):
Definition requirements of function build_profile() Provides a first and last name, while allowing the user to provide as many name-value pairs as desired. The two asterisks in the parameter **user_info tell Python to create an empty dictionary named user_info and encapsulate all name-value pairs received into this dictionary. In this function, the name-value pairs in user_info can be accessed like any other dictionary.
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. To define a function in Python, you can use required parameters, default parameters, variable parameters, and keywords Parameters and named keyword parameters, these five parameters can be used in combination. But please note that the order of parameter definition must be: Required parameters, default parameters, variable parameters, named keyword parameters and keyword parameters.
2. Python's functions have very flexible parameter forms, which can not only implement simple calls, but also pass in very complex parameters.
3. The default parameters must use immutable objects. If they are variable objects, there will be logic errors when the program is running!
4. Pay attention to the syntax for defining variable parameters and keyword parameters:
5.*args is a variable parameter, and args receives a tuple;
6 .**kw is a keyword parameter, and kw receives a dict.
7. And the syntax of how to pass in variable parameters and keyword parameters when calling a function:
The variable parameters can be passed in directly: func(1, 2, 3), or You can assemble the list or tuple first, and then pass it in through *args: func(*(1, 2, 3));
The keyword parameters can be passed in directly: func(a=1, b=2 ), you can assemble the dict first and then pass it in through **kw: func(**{'a': 1, 'b': 2}).
Using *args and **kw is the idiom of Python. Of course, other parameter names can also be used, but it is best to use the idiom.
8.5.4 Recursive parameters
Within a function, other functions can be called. If a function calls itself internally, the function is recursive. The advantages of recursive functions are simple definition and clear logic. Theoretically, all recursive functions can be written in a loop, but the logic of loops is not as clear as recursion.
def fact(n): if n==1: return 1 return n * fact(n - 1)
|
When using recursive functions, care must be taken to prevent stack overflow. In computers, function calls are implemented through the data structure of the stack. Whenever a function call is entered, a layer of stack frames is added to the stack. Whenever a function returns, a layer of stack frames is subtracted from the stack. Since the size of the stack is not infinite, too many recursive calls will cause stack overflow.
The movement of the Tower of Hanoi can be implemented very simply using recursive functions.
8.6 Higher-order functions
8.6.1 Higher-order functions
Since variables can point to functions and the parameters of functions can receive variables, then a function can receive another function As parameters, this kind of function is called a higher-order function.
def add(x, y, f):
return f(x) + f(y)
|
8.6.2 Built-in functions
1. The function abs() that finds the absolute value has only one parameter.
2. To determine the object type, use the type() function:
##>>> type(123)>>> type('str')> >> type(None)
| ## 3. To calculate the square root, you can call math .sqrt() function.
4.lower() returns a lowercase string.
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
| 6.max function max() can receive any number of parameters and return the largest that. 7. If you want to get all the properties and methods of an object, you can use the dir() function, which returns a list containing strings. For example, to get all the properties and methods of a str object: 8.Python’s built-in hex() function converts an integer into a string represented by hexadecimal. 9. For class inheritance relationships, it is very inconvenient to use type(). To determine the type of class, we can use the isinstance() function. Parameter types are checked and only integer and floating point type parameters are allowed. Data type checking can be implemented using the built-in function isinstance(). Use the built-in isinstance function to determine whether a variable is a string. 10. With getattr(), setattr() and hasattr(), we can directly manipulate the state of an object.
##>>> hasattr(obj, 'x') # Is there attribute 'x'? True
>>> obj.x
9
>>> hasattr(obj, 'y') # Yes Attribute 'y'?
False
>>> setattr(obj, 'y', 19) # Set an attribute 'y'
>>> hasattr( obj, 'y') # Is there an attribute 'y'?
True
>>> getattr(obj, 'y') # Get attribute 'y'
19
>> > obj.y # Get the attribute 'y'
19
| Through a series of built-in functions, we can manipulate any Python object Analyze it and get its internal data. It should be noted that we will only obtain object information when we do not know the object information. 11.Python has built-in map() and reduce() functions. map applies the passed function to each element of the sequence in turn 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]
reduce usage. Reduce applies a function to a sequence [x1, x2, x3, ...]. This function must receive two parameters. Reduce continues the cumulative calculation of the result with the next element of the sequence. |
##>>> from functools import reduce
>>> def fn(x, y):... return x * 10 + y
...
>>> reduce(fn, [1, 3, 5, 7, 9])
13579
12.Python’s built-in filter() function is used to filter sequences. filter() also receives a function and a sequence . Unlike map(), filter() applies the passed function to each element in turn, and then decides to retain or discard the element based on whether the return value is True or False. The key is to correctly implement a "filter" function. Note that the filter() function returns an Iterator, which is a lazy sequence, so to force filter() to complete the calculation results, you need to use the list() function to obtain all the results and return the list.
def is_odd(n):
return n % 2 == 1
list (filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# Result: [1, 5, 9, 15]
|
13.Python’s built-in sorted() function can sort the list.
##>>> sorted([36, 5, -12, 9, -21])[-21, -12, 5, 9, 36]
| 14. The sorted() function is also a higher-order function, and it can also receive a key function to implement customization sorting, such as sorting by absolute value. To perform reverse sorting, you do not need to change the key function. You can pass in the third parameter reverse=True.
##>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']
|
15. Python built-in The enumerate function can turn a list into an index-element pair, so that both the index and the element itself can be iterated in a for loop.
16. The round() function can return any decimal place.
8.6.3 Decorator
The way to dynamically add functionality while the code is running is called "Decorator". Essentially, a decorator is a higher-order function that returns a function. Decorator: Add new functionality without changing the function itself.
The function object has a __name__ attribute, you 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 Attribute call:
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 be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
@property is widely used in class definitions, allowing callers to write short codes while ensuring necessary checks on parameters. In this way, the possibility of errors is reduced when the program is running.
The @unique decorator can help us check to ensure that there are no duplicate values.
8.7 Store functions in modules
In order to write maintainable code, you can group many functions into different files, so that the code contained in each file is relatively less. In Python, a .py file is called a module (Module).
One of the advantages of functions is that they allow you to separate blocks of code from the main program. By giving functions descriptive names, you make the main program much easier to understand. You can go one step further and store the functions in separate files called modules, and then import the modules into the main program. The import statement allows the code in the module to be used in the currently running program file.
By storing functions in separate files, 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. By storing functions in separate files, you can share those files with other programmers rather than the entire program. Knowing how to import functions also allows you to use function libraries written by other programmers.
In order to avoid module name conflicts, Python has introduced a method of organizing modules by directory, called a package. After the package is introduced, as long as the top-level package name does not conflict with others, all modules will not conflict with others. Now, the module name of abc.py becomes mycompany.abc, and similarly, the module name of xyz.py becomes mycompany.xyz.
Note that there will be an __init__.py file under each package directory. This file must exist. Otherwise, Python will treat this directory as a normal directory instead of a package. __init__.py can be an empty file, or it can have Python code, because __init__.py itself is a module, and its module name is mycompany.
8.7.1 Import the entire module
To make the function importable, you must first create the module. Modules are files with a .py extension that contain code to be imported into a program.
if __name__=='__main__':
test()
| The first step to use a module is to import the module. When we run the hello module file on the command line, the Python interpreter sets a special variable __name__ to __main__, and if the hello module is imported elsewhere, The if judgment will fail, so this if test allows a module to execute some additional code when run through the command line, the most common is to run tests.
8.7.2 Scope
In a module, we may define many functions and variables, but some functions and variables we hope to be used by others, and some functions and variables we hope Only used inside the module. In Python, this is achieved through the _ prefix. Normal function and variable names are public and can be directly referenced, such as: abc, x123, PI, etc.; variables like __xxx__ are special variables and can be directly referenced, but have special purposes, such as the above __author__ and __name__ are special variables. The document comments defined by the hello module can also be accessed with the special variable __doc__. Generally, we should not use this variable name for our own variables; functions or variables like _xxx and __xxx are Non-public (private) should not be quoted directly, such as _abc, __abc, etc.;
Private functions or variables should not be quoted by others, so what is their use? Please see 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 a private function. In this way, when calling the greeting() function, we don’t need to worry about the details of the internal private function. This is also a very useful code encapsulation and abstraction. method, that is: all functions that do not need to be referenced from the outside are defined as private, and only functions that need to be referenced from the outside are defined as public.
8.7.3 Import specific modules
Store multiple functions in a module, separated by commas, you can import any number of functions from the module.
8.7.4 Use as to specify an alias for a function
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 function's name 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 importing it.
8.7.5 Use as to specify an alias for the module
You can also specify an alias for the module. By giving the module a short alias (such as assigning the alias p to the pizza module), you can more easily call 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
Using the asterisk (*) operator allows Python to import all functions in the module.
However, when using a large module that you did not write yourself, it is best not to use this import method: if there are functions in the module with the same names as those used in your project, it may lead to unexpected results: Python may encounter multiple functions or variables with the same name and overwrite the function instead of importing all functions separately.
8.8 Function Writing Guide
When writing functions, you need to keep several details in mind.
1. Functions should be given descriptive names and only lowercase letters and underscores should be used in them. Descriptive names help you and others understand what the code is trying to do. The above convention should also be followed when naming modules.
2. Each function should contain a comment that briefly explains its function. The comment should follow the function definition and use the docstring format . A well-documented function allows other programmers to use it simply by reading the description in the docstring: they can trust that the code will work as described; as long as they know the name of the function, the required arguments, and the type of the return value, You can use it in your own programs.
3.When specifying a default value for a formal parameter, there should be no spaces on either side of the equal sign.
|
|
|
|
|