Basis and application of function

Posted by aragon1337 on Fri, 07 Jan 2022 12:22:36 +0100

catalogue

  • Scope of namespace

  • Use of global and nonlocal keywords

  • Function object (function name)

  • Nested calls to functions

  • Nested definition of functions

  • Closure function (emphasis)

  • Concept of decorator (key points)

 

Scope of namespace

Scope: the scope of a namespace

Built in namespace

It can be used anywhere at any stage of the program (globally valid)

Global namespace

It can be used anywhere at any stage of the program (globally valid)

Local namespace

In general, it is only valid in the respective local namespace

 

Use of global and nonlocal keywords

# x = 111
# def index():
#     # Local modification of global variables requires keyword declaration
#     global x
#     x = 222
# index()
# print(x)


# name_list = ['jason', 'kevin']
# def index():
#     name_list.append('heiheihei')
# index()
# print(name_list)
"""
If you want to modify the global data locally
    If the data is immutable, a keyword is required global statement
    If the data is of variable type, no keyword is required global statement
"""
def index():
    # x = 111
    l1 = [11,22]
    def func():
        # Internal local modify external local
        # nonlocal x
        # x = 333
        l1.append(333)
    func()
    print(l1)
index()
"""
If you want to modify the immutable type data of the external part in the internal part
 Keyword required nonlocal statement
"""

  

Function object (function name)

When the function name encounters parentheses, it will be called!!!

  1. Function names can be assigned as variable names

    def index():
        print('from index')
    a = index
    a()  # The essence is to call the index function
    

      

  2. Function names can also be used as arguments to functions
    def index():
        print('from index')
    def func(a):
        print(a)
        a()
        print('from func')
    func(index)
    

      

  3. The function name can also be used as the return value of the function
    def index():
        print('from index')
    
    
    def func():
        print('from func')
        return index
    
    
    res = func()  # Call func and accept the return value of func
    res()
    

      

  4. The function name can be used as an element of the container type (multiple data can be stored inside)
    def index():
        print('from index')
    
    
    l = [111, 222, 333, index()]
    print(l)
    

      

  5. case
    def register():
        print('Registration function')
    def login():
        print('Login function')
    def shopping():
        print('Shopping function')
    def transfer():
        print('Transfer function')
    def withdraw():
        print('Withdrawal function')
    def check_order():
        print('View order')
    func_dic = {'1':register,
                '2':login,
                '3':shopping,
                '4':transfer,
                '5':withdraw,
                '6':check_order
                }
    while True:
        print("""
        1.Registration function
        2.Login function
        3.Shopping function
        4.Transfer function
        5.Withdrawal function
        6.View order
        """)
        choice = input('Please enter the function number>>>:').strip()
        # Judge whether the number entered by the user is in the k of the dictionary
        if choice in func_dic:
            # Get value from key (function name)
            func_name = func_dic.get(choice)
            # The function name is called in parentheses
            func_name()
        else:
            print('Function number does not exist')
    
        # The disadvantage of the following code is that the code is too complex when there are many functions
        # if choice == '1':
        #     register()
        # elif choice == '2':
        #     login()
        # elif choice == '3':
        #     shopping()
        # else:
        #     print('tired of writing ')
    

      

Nested calls to functions

Nested call: call other functions inside a function
  

# def index():
#     print('from index')
# def func():
#     index()
#     print('from func')
# func()

def my_max(a, b):
    if a > b:
        return a
    return b

def many_max(x,y,z,m):
    res = my_max(x,y)
    res1 = my_max(res,z)
    res2 = my_max(res1,m)
    return res2
ret = many_max(1,2,3,4)
print(ret)7

  

Nested definition of functions

Other functions are defined inside the function body

Hide all complex functions and expose a simple interface

def all_func(type):
    def register():
        print('Registration function')
    def login():
        print('Login function')
    def transfer():
        print('Transfer function')
    def shopping():
        print('Shopping function')
    # Here is only the phenomenon of delay nested definition, and optimization is not considered for the time being
    if type == '1':
        register()
    elif type == '2':
        login()
    elif type == '3':
        transfer()
    elif type == '4':
        shopping()
    else:
        print('I don't know what function')

all_func('3')

  

Closure function

Closed: a function defined inside a function

Package: the internal function uses the name in the external function namespace

Only those functions that meet the above two characteristics can be called closure functions

def outer():
    x = 222

    def index():
        print('from index', x)

    return index

  

Closure functions are actually the second way to pass parameters to functions

Method 1: the function body code needs data, and the formal parameters can be defined directly in parentheses

def index(username):
    print(username)
def my_max(a, b):
    if a > b:
        return a
    return b

  

Method 2: using closure function

def outer(x,y):
    # x = 2
    # y = 40
    def my_max():
        if x > y:
            return x
        return y
    return my_max
res = outer(2,40)
print(res())
print(res())

  

 

Concept of decorator

Decorator is not a new knowledge, but a combination of namespace function object closure function we learned before

Decorator: refers to tool decoration: adding additional functions to the decorated object

Principle of decorator development of open and closed principle: open and close to extension: modify the core idea of closed decorator and add additional functions without changing the "internal code of decorated object" and "original calling method"

def index():
    print('from index')
index()

  

import time

# print(time.time())  # 1637036293.0609405
# The result obtained is called a timestamp (the number of seconds from 1970-1-1 at the moment the code is run)
# time.sleep(3)  # Let the program wait in place for 3 seconds
# print('sleep full ')


def index():
    time.sleep(3)
    print('from index')
# Count the execution time of the index function
# Count the time before the function runs
start_time = time.time()
index()
# Count again after the function runs
end_time = time.time()
# Calculate difference
print(end_time - start_time)