Python中的装饰器——11

装饰器

什么是装饰器

装饰他人的器具,本身可以是任意可调用对象,被装饰者也可以是任意可调用对象

原则

--- 不修改被修饰函数的源代码

--- 不修改被修饰函数的调用方式

装饰器的目标

在遵循原则的基础上为被装饰对象添加新功能

无参装饰器

import time#导入time模块

def timmer(func):
    def wrapper():
        start_time = time.time()#开始的时间
        res = func()
        stop_time = time.time()#结束的时间
        print('run time is %s'%(stop_time-start_time))#打印运行时间
        return res
    return wrapper

@timmer
def test():
    time.sleep(1)
    print('from test')

test()

简易验证登录状态的装饰器

user_list = [
    {'name':'ahe520','passwd':'6201134'},
    {'name':'xl520','passwd':'123'},
    {'name':'hzz520','passwd':'12345'}
]#存放用户名密码的列表
current_dic = {'username':None,'userlogin':False}#登录状态

def auth_func(func):
    def warpper(*args,**kwargs):
        if current_dic['username'] and current_dic['userlogin']:
            res = func(*args,**kwargs)
            return res
        username = input('请输入用户名:')
        userpasswd = input('请输入密码:')
        for user_dic in user_list:
            if username ==user_dic['name'] and userpasswd == user_dic['passwd']:
                current_dic['username'] = username
                current_dic['userlogin'] = True
                res = func(*args,**kwargs)
                return res
        else:
            print('用户名或密码错误')
    return warpper

def index():
    print('欢迎进入主页')
@auth_func
def home():
    print('欢迎回家')
@auth_func
def shipping_car():
    print('购物车里有[%s],[%s],[%s]'%('牛奶','饮料','啤酒'))

index()
home()
shipping_car()

猜你喜欢

转载自www.cnblogs.com/winsdom/p/9133316.html