This example shows how Python uses function defaults to implement static variables of functions, as follows:
A, Python function default value
The use of the Python function defaults can be handy for writing code when a function is called, and many times we just use the default value. So a lot of the function defaults are used in Python, especially in the middle of a class, where the default values are used by a bunch of class initialization functions. You can easily create classes when you use classes without passing a bunch of parameters.
As long as you add "=defalut_value" to the function parameter name, the default value of the function is defined. One place to note is that a parameter with a default value must be at the end of the list of function arguments, not allowing an argument with no default value to be placed with a default value, because if you do that, the interpreter will not know how to pass the argument.
Let's take a look at a sample code:
def ask_ok (prompt, retries=4, complaint= ' Yes or No, please! '): While
True:
OK = raw_input (prompt)
if OK in (' Y ', ' ye ', ' yes ': return True
if OK in (' n ', ' No ', ' nop ', ' Nope '): return False
retries = retries-1
if Retrie s < 0:raise ioerror, ' refusenik user '
print complaint
When you call the above function, you can modify the number of retries and the output of the prompt language, if you are more lazy, then nothing to change.
Second, Python uses the function default value to realize function static variable function
Static variables are not supported in Python, but we can implement the function of static variables through the default value of the function.
When the default value of a function is a class with a variable content, the contents of the class are variable, and the name of the class does not change. (The amount of memory that is created is unchanged, and the content can change).
This is because the default value of functions in Python is only executed once, and static variable initialization is executed once, as is the case with static variables. This is what they have in common.
Let's take a look at the following program fragment:
Def f (A, l=[]):
l.append (a) return
L
print f (1)
print F (2) print F (
3)
print f (4,[' X '))
Print F (5)
Its output results are:
[1]
[1, 2]
[1, 2, 3]
[' X ', 4]
[1, 2, 3, 5]
Before the good understanding, why the final "Print F (5)" Output is "[1, 2, 3, 5]"?
This is because "Print f (4,[' X ']"), the default variable is not changed because the initialization of the default variable is only performed once (the first time using the default), and the memory area (which we can call the default variable) that initializes the execution is not changed, so the final output is "[1, 2 , 3, 5] ".
I believe that the examples described in this paper will help us in Python programming.