Python3.5装饰器典型案例分析
本文通过Python3.5实例详解装饰器原理。涵盖无参函数、带参函数及混合函数的装饰器写法,利用高阶函数与嵌套函数实现功能增强。代码展示如何使用*args和**kwargs处理不同参数情况,并演示计时器装饰器的具体应用与运行结果。
Python3.5装饰器基础示例
本文通过具体实例解析Python3.5中装饰器的应用,供读者参考学习。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
#高阶函数+嵌套函数==>装饰器
import time
def timer(func): #timer(test1)-->func=test1
def decor():
start_time = time.time()
func() #run test1
stop_time = time.time()
print("the run time of func is %s" %(stop_time-start_time))
return decor
@timer #test1 = timer(test1)
def test1():
time.sleep(3)
print("in the test1")
@timer #test2 = timer(test2)
def test2():
time.sleep(3)
print("in the test2")
print(timer(test1)) #打印deco的地址
#test1 = timer(test1)
#test2 = timer(test2)
test1() #-->执行decor
test2()
程序执行输出如下:
<function timer.<locals>.decor at 0x00B720C0> in the test1 the run time of func is 3.000171661376953 in the test2 the run time of func is 3.000171661376953
处理带参函数的装饰器
1、装饰器修饰有参数函数
#高阶函数+嵌套函数==>装饰器
import time
def timer(func): #timer(test1)-->func=test1
def decor(arg1,arg2):
start_time = time.time()
func(arg1,arg2) #run test2
stop_time = time.time()
print("the run time of func is %s" %(stop_time-start_time))
return decor
@timer #test2 = timer(test2) = decor test2(name)==>decor(name)
def test2(name,age):
print("test2:",name,age)
test2("liu",23)
运行结果如下:
test2: liu 23 the run time of func is 0.0
通用参数组装饰器应用
2、装饰器修饰多个函数,有的函数带参数,有的函数不带参数的情况(采用参数组)
#高阶函数+嵌套函数==>装饰器
import time
def timer(func): #timer(test1)-->func=test1
def decor(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs) #run test1
stop_time = time.time()
print("the run time of func is %s" %(stop_time-start_time))
return decor
@timer #test1 = timer(test1)
def test1():
time.sleep(3)
print("in the test1")
@timer #test2 = timer(test2) = decor test2(name)==>decor(name)
def test2(name,age):
time.sleep(1)
print("test2:",name,age)
#test1 = timer(test1)
#test2 = timer(test2)
test1() #-->执行decor
test2("liu",23)
运行结果:
in the test1 the run time of func is 3.0036065578460693 test2: liu 23 the run time of func is 1.0084023475646973
更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













