编程语言
首页 > 编程语言> > python菜鸟学习: 11. 装饰器的基础用法

python菜鸟学习: 11. 装饰器的基础用法

作者:互联网

# -*- coding: utf-8 -*-
# decorator
# 定义:本质是函数,就是为其他函数添加附件功能
# 原则:
# 1.不能修改被装饰的函数的源代码
# 2.不能修改被装饰的函数的调用方式
# 实现装饰器
# 1.函数既变量
# 2.高阶函数
# 3.嵌套函数
# 高阶甘薯+嵌套函数--->装饰器
import time


# 计算函数运行时间装饰器:参数中包含函数
def countTime(func):
start_Time = time.time()
func()
end_Time = time.time()
print("then func run time is %s" % (end_Time - start_Time))
# return func # 返回func的内存地址


# 调用装饰器countTime
@countTime
def bar():
print("this is bar")
time.sleep(2)


# # 在bar中增加时间打印,从而在内存地址中覆盖原来的bar函数地址,并且原来的bar函数不变
# bar = countTime(bar)
# bar()


####高阶函数+嵌套函数####
def timer(func):
def countTime(*args, **kwargs):
start_Time = time.time()
func(*args, **kwargs)
end_Time = time.time()
print("then func run time is %s" % (end_Time - start_Time))

return countTime # 返回func的内存地址


@timer # timer(test1)
def test1():
time.sleep(3)
print("this is test1")


@timer
def test2(*args, **kwargs):
time.sleep(4)
print("test2 vlues :%s %s" % (str(*args), dict(**kwargs)))


test1()
test2("liyuzhou")

标签:11,countTime,bar,函数,python,菜鸟,Time,func,time
来源: https://www.cnblogs.com/liyuzhoupan/p/16620091.html