1.装饰器
def desc(fun):
def add_info():
print(‘hello hahaha~’)
fun()
return add_info
@desc #给函数添加装饰器
def login():
print(‘login…’)
@desc
def logout():
print(‘logout…’)
login()
logout() #调用函数
2.装饰器特点:
对修改是封闭的,对扩展是开放的
import time #导入时间模块
def f1():
print(‘This is a function…’)
def f2():
print(‘This is a function…’)
def print_current_time(func):
print(time.time())
func()
print_current_time(f1)
print_current_time(f2)
3.多个装饰器
“”"
* coding:utf-8 *
Name:09_多个装饰器.py
Date:19-3-31
Author:westos-wsp
Connect:zyj919@sina.com
Desc:
“”"
def decorator_a(fun):
print(‘Get in decorator_a’)
def inner_a(*args, **kwargs):
print('Get in inner_a')
res = fun(*args, **kwargs)
return res
return inner_a
def decorator_b(fun):
print(‘Get in decorator_b’)
def inner_b(*args, **kwargs):
print('Get in inner_b')
res = fun(*args, **kwargs)
return res
return inner_b
@decorator_b
@decorator_a
def f(x):
print(‘Get in f’)
return x * 2
f(2)