Python3 Basics - Function 2

Higher order functions

in principle

  • The parameter received by the function is a function

  • The return value of a function is a function

Example

Example 1: The receiving value is a function

def A():
    print("I am A")
    return
def B(x):
    print("I am B")
    return
B(A())
I am A
I am B

Example 2: The return value is a function

def A():
    print("I am A")
    return
def B():
    return A()
B()
I am A

Example 3: Adding functionality to a function

import time
def time_con(a):
    start_time = time.time()
    a()
    stop_time = time.time()
    print("这个函数运行的时间是%s" % (stop_time - start_time))
def test():
    time.sleep(3)
    print("I am test!!!")
time_con(test)
I am test!!!
这个函数运行的时间是3.000800848007202

function nesting

Using a function as an argument to another function is a nested function

Example

def a():
    print("函数第一层")
    def b():
        print("函数第二层")
        def c():
            print("函数第三层")
        c()
    b()
a()
函数第一层
函数第二层
函数第三层

Closure

  • A closure is an entity composed of a function and its associated reference environment

  • The role of closures in improving code reusability

closure, i.e. a complete closed function

def test(x):                            #自定义函数
    a = "您输出的是:"                   #函数中封装的变量
    print(a,x)                          #函数体
    return x                            #返回值
test("测试字符")                        #运行函数
您输出的是: 测试字符                     #运行结果

function variable scope

  • L (Local) local scope
  • E (Enclosing) in the function outside the closure function
  • G (Global) global scope
  • B (Built-in) built-in scope

in principle

Search according to the rules of L –> E –> G –>B, that is: if you can’t find it locally, you will go to the local outside the local (such as closure), if you can’t find it, you will go to the global search, and then go to Find in built-in.

Example

Example 1

name = '小明'                 #定义变量
def foo():                    #定义函数
    name = '小花'                 #定义函数中内容
    def bar():                    #定义函数中子变量
        name = '小黄'                 #定义函数自变量内容
        print(name)                   #打印函数变量内容
    return bar()                  #返回定义的函数内容
foo()                        #运行函数
小黄

Example 2

name = '第一层'
def foo():
    name = '第二层'
    def bar():
        name = '第三层'
        def tt():
            print(name)
        return tt
    return bar
foo()()()
第三层

decorator

Decorators are essentially functions, and functions are additional functions for other functions

Decorator = higher order function + function nesting + closure

in principle

  • Do not modify the source code of the decorated function
  • Do not modify the calling method of the decorated function

###Demo

def 装饰器(a):
    def 装饰器内容(*args,**kwargs):
        print("装饰器附加内容1")
        原函数执行 = a(*args,**kwargs)
        print("装饰器附加内容2")
        return 原函数执行
    return 装饰器内容
@装饰器
def test(参数):
    print('这是原有函数内容和%s!!!' %参数)
    return ("原函数返回值")
print(test("测试参数"))

Example

Primitive

def test():
    time.sleep(3)
    print('This is test!!!')
This is test!!!

After building the decorator with the time module

import time                                                     #调用time模块儿
def time_func(a):                                               #定义变量用于接收函数参数
    def time_con(*args,**kwargs):                                   #定义装饰器用于变更函数输出
        start_time = time.time()                                    #记录运行开始时间
        res = a(*args,**kwargs)                                     #被调用的函数赋值
        stop_time = time.time()                                     #记录函数运行结束时间
        print("这个函数运行的时间是%s" %(stop_time - start_time))   #计算并打印记录时间
        return res                                                  #运行函数返回值
    return time_con                                                 #返回装饰器运行后值
@time_func                                                      #语法糖,相当于 test = time_func(test)
def test(a,b):                                                  #用于测试的自定义函数
    time.sleep(3)                                                   #延迟执行3秒(用于测试)
    print("这是个测试函数,第一个参数是%s第二个参数是%s" %(a,b))    #打印测试语句
    return ('【函数运行完毕】')                                     #函数返回值
print(test("【参数1】","【参数二】"))                           #执行装饰后的函数

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324950468&siteId=291194637