先说一下,Python3中的装饰器优点:在不修改原本函数内容前提下,可以对功能进行扩展。比如说:你的前队友已经写好了这个函数,一旦你通过修改这函数来做功能扩展,肯定会出现bug的,所以就得用到 Python3 中的装饰器。
其实Python3的装饰器本质上是利用了
- 嵌套 + 闭包
- @xx语法
代码例子
def outer(func):
def inner():
# 在这里可以添加你要的功能
res = func() # 这是调用原本的函数
# 在这里也可以添加你要的功能
return res
return inner
@outer # 其实这个叫法是 show = outer(show)
def show():
print("show function")
return 11
v1 = show()
print(v1)
举个例子
import time
def calculateTime(func):
def inner():
start = time.time()
res = func()
end = time.time()
interval = start - end
print(f"the function name {func}, the time interval: {interval}")
return res
return inner
@calculateTime
def f1():
for i in range(99999):
pass
def f2():
for i in range(10000):
pass
f1()
f2()
# 输出结果
# 结果完全符合预期,只有函数 f1 才用了 calculateTime 函数
the function name <function f1 at 0x0000020D3EABA160>, the time interval: -0.001027822494506836
第二个例子
import os
def checkFile(func):
def inner(file_path):
if not os.path.exists(file_path):
return None
res = func(file_path)
return res
return inner
@checkFile
def readFile(file_path):
f = open(file_path. mode='r', encoding='utf-8')
data = f.read()
f.close()
return data
print(read_info("test.txt"))
给个赞呗~