# Author : XueFeng
# 定义:本质是函数,,(装饰其他函数),就是为其他函数添加附加功能
# 原则: 1.不能修改被装饰函数的源代码
# 2.不能修改被装饰函数的调用方式
# 实现装饰器知识储备:
# 1.函数即’变量‘
# 2.高阶函数
# 3.嵌套函数
# 高阶函数+嵌套函数=》装饰器
def logger():
print('logging')
def test1():
pass
logger()
def test2():
pass
logger()
test1()
test2()
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 test1')
test1()
# 这里解释的是函数即变量的意思
# 调用函数放在最后面,定义函数位置可以交换
# 相当于:
# x=2 y=3
# y=3 x=2
# print(x,y) print(x,y)
def f1():
f2()
return 0
def f2():
print('this is the test')
f1()
# 这里对高阶函数进行重新解释
# a. 传递实参
def test1(func):
print(func)
func()
def bar():
print('jim is me')
test1(bar)
# b.传递返回值
import time
def timmer1(func):
start_time = time.time()
func()
stop_time = time.time()
print('the func run time is %s' % (stop_time - start_time))
return func # 返回函数func地址
def bar():
time.sleep(3)
print('bar')
t = timmer1(bar) # 把函数体func的地址传给t
t() # 用t替代bar指向函数体
# 嵌套函数
x=0
def nam():
x=1
def nam1():
x = 2
def nam2():
x = 3
print(x)
nam2()
nam1()
nam() # 就近原则
python_详解装饰器
最新推荐文章于 2025-09-12 11:28:05 发布

8万+

被折叠的 条评论
为什么被折叠?



