Python USES the default values of functions to implement methods for static variables of functions

  • 2020-04-02 13:58:56
  • OfStack

The example of this article shows how Python USES the default value of functions to implement static variables of functions. The specific method is as follows:

The default value of Python functions

The use of default values for Python functions makes it easy to write code when a function is called, and many times we just use the default values. So function defaults are used a lot in python, especially in the middle of a class, where they are used in class initializers. Classes can be easily created without passing a bunch of arguments.

Simply add "=defalut_value" after the function parameter name and the function default is defined. One thing to note is that arguments with default values must be at the end of the list of function arguments. It is not allowed to put arguments without default values after arguments with default values, because if you define them that way, the interpreter will not know how to pass the arguments.

Let's start with 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 retries < 0: raise IOError, 'refusenik user'
    print complaint

When you call the above function, you can change the number of retries and the prompt language for the output, and if you are lazy, you don't have to change anything.

Python USES the default value of the function to realize the function static variable function

Static variables are not supported in Python, but they can be implemented using the default values of functions.
When the default value of a function is that the contents of the class are mutable, the contents of the class are mutable and the name of the class is unchanged. The equivalent area of memory is unchanged, while its contents can change.
This is because the default value of a function in python is executed only once (static variable initialization is executed once, just like static variables). That's what they have in common.

Take a look at the following program snippet:


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)

The output is:


[1]
[1, 2]
[1, 2, 3]
['x', 4]
[1, 2, 3, 5]

It is easy to understand why the output of "print f(5)" is "[1, 2, 3, 5]".

This is because when "print f(4,['x'])", the default variable is not changed, because the initialization of the default variable is only performed once (the first time is called with the default value), and the memory area created by the initialization execution (we can call it the default variable) is not changed, so the final output is "[1, 2, 3, 5]".

I believe that the examples described in this article are helpful to the Python programming.


Related articles: