#author F
#装饰器: 本质是函数 为其他函数添加功能 文章发表过程->前后添加->运营添加->...
#已经上线 100个函数用到 需要修改
#装饰器原则: 1.不能修改被装饰函数的代码
# 2.不能修改被装饰的函数的调用方式
#也即: 装饰器对被装饰函数是透明的 对被装饰函数完全不影响
import time
'''
def timmer(func):
def warpper(*args, **kwargs):
start_time = time.time()
func()
stop_time = time.time()
print("the func run time is %s" %(stop_time-start_time))
return warpper
@timmer
def test1():
time.sleep(3)
print("in the test 1")
# test1()
#装饰器需要的认识
#1.*函数即变量* __匿名函数
#2.高阶函数
# a:把一个函数名当作实参传给另一个函数 (在不修改被装饰函数源代码的情况下为其添加功能)
# b:返回值中包含函数名 (不修改函数的调用方式)
#3.函数嵌套
#高阶函数+函数嵌套 -> 装饰器
#函数在使用过程中分为两步: 第一是定义 第二是调用
#怎么写一个高阶函数?
# 1.写一个形参
# 2.函数当作实参传入
def bar():
print("in the bar")
def test2(func):
print(func)
# test2(bar) #打印函数所在的内存地址
#在返回值中包含函数
def barr():
time.sleep(1)
print("in the barr")
def test3(func):
print(func) #打印函数的返回地址
return func #返回函数的内存地址
# print(test3(barr)) #区别 test3(barr) 和 test3(barr()) 前者传的是函数的地址 后者传递的是函数的返回值
# t = test3(barr) #返回barr的地址
# t() #调用地址 运行函数
#嵌套函数
#在函数体内再次定义另一个函数 注意和函数调用的区别
def foo():
print("in the foo")
def bara():
print("in the bar")
#bara() #无法调用 函数的 局部特性
bara()
foo()
#注意函数的嵌套和函数的调用的区别:
# def test_1():
# test_2() #这个是函数的调用 不是函数的嵌套
'''
#######################################装饰器########################################
#step1:
# def deco(func):
# start_time = time.time()
# func()
# stop_time = time.time()
# print("the function cost %s" %(stop_time-start_time))
#step2:
# def deco(func):
# start_time = time.time()
# return func
# stop_time = time.time()
# print("the function cost %s" %(stop_time-start_time))
#step3
def timer(func):
def deco():
start_time = time.time()
func()
stop_time = time.time()
print("the function cost %s" %(stop_time-start_time))
return deco
@timer
def test1():
time.sleep(1)
print('in the test1')
@timer
def test2():
time.sleep(2)
print('in the test2')
# test1()
# test2()
#step1: 不修改函数的源代码 添加新功能
# deco(test1)
# deco(test2)
#step2: 不修改函数的调用方式 但没有完成新功能
# test1 = deco(test1)
# test2 = deco(test2)
# test1()
# test2()
#step3: 函数嵌套整合两者
# test1 = timer(test1)
# test2 = timer(test2)
# test1()
# test2()
test1()
test2()
#自我总结: 装饰器其实是把被装饰函数放到一个装饰用的函数中加工处理 然后在这个装饰函数外层包裹一个函数 用来返回这个装饰函数的地址
Python装饰器
最新推荐文章于 2023-06-20 22:11:03 发布