# Author Richard_Kong
# !/usr/bin/env python
# --*-- encoding:utf-8 --*--
"""
装饰器:本质是函数,(装饰其他函数),就是为其他函数添加附加功能的
原则:1、不能修改被修饰函数的源代码
2、不能修改该被修饰函数的调用方式
装饰器对被修饰的函数是透明的,就是函数不知道装饰器的存在
如何写装饰函数:
1、函数即变量
2、高阶函数
1) 把一个函数名当成实参传给另外一个函数
2) 返回值中包含函数名
3、嵌套函数
高阶函数+嵌套函数 =====>>>>>:利用这两个就可以实现一个装饰器
"""
import time
def timmer(func):
"""
:param func:
:return:warpper
"""
def warpper(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs) # have can shu de shihou yong
stop_time = time.time()
print("function running time is %s"%(stop_time-start_time))
return warpper
@timmer
def test1():
time.sleep(3)
print("in function test1")
@timmer
def test2(name,age):
time.sleep(2)
print("in test2 name:",name,age)
# @timmer equals test1 = timmer(test1)
test1()
test2("hafbaj","dafbg")
参考博客:
https://www.cnblogs.com/huchong/p/7725564.html
python装饰器之基础型
最新推荐文章于 2024-06-10 15:06:19 发布