python3 装饰器

'''装饰器的固定格式'''
def wrapper(func):
    def inner(*args, **kwargs):
        print("执行前")
        ret = func(*args, **kwargs)
        print("执行后")
        return ret
    return inner

@wrapper #func = wrapper(func)
def func():
    print("func is running...")

func()

执行结果:
执行前
func is running...
执行后

'''带参数的装饰器'''
def wrapper(flag):
def outer(func):
def inner(*args, **kwargs):
if flag:
print("在之前.")
ret = func(*args, **kwargs)
print("在之后")
return ret
else:
return func(*args, **kwargs)
return inner
return outer

@wrapper(1) # 先执行wrapper(1),返回outer,@outer就是语法糖
def func():
print("func is running...")

@wrapper(0) #先执行wrapper(0),返回outer,@outer就是语法糖
def func2():
print("func2 is running...")

func()
func2()
执行结果:
在之前.
func is running...
在之后
func2 is running..

'''写日志'''
def record_log(file):
def log(fn):
def inner(*args, **kwargs):
ret = fn(*args, **kwargs)
with open(file, mode="a", encoding="utf-8") as f: #记录日志
f.write("调用函数: %s" % fn.__name__)
return ret
return inner
return log

@record_log('func1.txt')
def func1(): # 日志放在func1.txt
print("我是func1")

@record_log('func2.txt')
def func2(): # 日志放在func2.txt
print("我是func2")

func1()
func2()

执行结果:
我是func1
我是func2

 

 

上一篇:Python三大神器:装饰器,迭代器,生成器


下一篇:leetcode - Minimum Window Substring