Python学习笔记:高阶函数(函数指针)与装饰器

来源:互联网 发布:mac 双定制粉底液 肤质 编辑:程序博客网 时间:2024/06/08 07:12

高阶函数

函数指针作为参数

函数可以作为参数传递给另一个函数,这是通过函数指针来实现的。在Python中,这称为高阶函数,函数名即为函数指针:

def func_1():    print("func_1 start running.")    print("func_1 runs over.")def func_2(func):    func()print("addr of func1():{}".format(func_1))       #函数名即为函数指针func_2(func_1)new_func=func_1     #此处的new_func相当于函数指针new_func()

函数指针作为返回值

def func_1():    print("func_1 start running.")    print("func_1 runs over.")def func_2(func):    print("this is a append feature.")    return funcfunc_1=func_2(func_1)   #此时func_2会运行func_1()

装饰器

装饰器是一种能为已有函数添加附加功能、又不会改变原函数的源码与调用方式的器具。可以看到上面函数指针作为返回值的代码段实现了添加功能又不改变源码与调用方式,但是实际上fun_2()与fun_1()不是在同一语句下执行的,fun_2()先于fun_1()执行。为实现原函数与装饰器同语句执行,可在fun_2()中再嵌套一层函数。

实现

import timedef timer(func):    def decorator():        start_time=time.time()        func()        end_time=time.time()        print("running time:{}".format(end_time-start_time))    return decoratordef fun_1():    print("fun_1 starts running...")    print("fun_1 runs over")fun_1=timer(fun_1)fun_1()

在timer()中并没有实际的执行语句,它只是返回了一个装饰器的函数指针。fun_1=timer(fun_1)语句将decorator()的函数地址覆盖了原函数fun_1()的地址,所以当执行fun_1()时,实际上执行的是decorator()。这样就实现了装饰器的功能。

Python装饰器

在Python中,调用装饰器的方法为在需要装饰的函数定义前面使用@装饰器,上述代码可改为:

import timedef timer(func):    def decorator():        start_time=time.time()        func()        end_time=time.time()        print("running time:{}".format(end_time-start_time))    return decorator@timerdef fun_1():    print("fun_1 starts running...")    time.sleep(3)    print("fun_1 runs over")fun_1()

带参数的函数

以上讨论的均是无参函数,若带参数的函数也需要用装饰器,则需要对装饰器代码进行修改。为使装饰器适应不同参数个数的函数,在装饰器中使用可变参数:

import timedef timer(func):    def decorator(*args, **kwargs):        start_time=time.time()        func(*args, **kwargs)        end_time=time.time()        print("running time:{}".format(end_time-start_time))    return decorator@timerdef fun_1(arg1,arg2):    print("fun_1 starts running...")    time.sleep(1)    print("fun_1 runs over")fun_1(1,2)

带参数的装饰器

阅读全文
0 0
原创粉丝点击