• 函数闭包带参数装饰器


    import time
    users_dic = [{'name':'zsz','passwd':'123'},
                {'name':'alex','passwd':'123'},
                {'name':'lhf','passwd':'123'}]
    current_dic = {"username":None,"Login":False}
    def auth(auth_type='filedb'):
        def auth_func(func):
            def wrapper(*args,**kwargs):
                print("认证方式是:",auth_type)
                if auth_type == 'filedb':
                    if current_dic["username"] and current_dic["Login"]:
                        res = func(*args,**kwargs)
                        return res
                    username = input("用户名:").strip()
                    passwd = input("密码:").strip()
                    for user_dic in users_dic:
                        if username == user_dic['name'] and passwd == user_dic['passwd']:
                            current_dic["username"] = username
                            current_dic["Login"] = True
                            res = func(*args, **kwargs)
                            return res
                    else:
                        print("用户名或者密码错误")
                elif auth_type == 'ldap':
                    start_time = time.time()
                    res = func(*args,**kwargs)
                    stop_time = time.time()
                    print("函数运行时间为%s秒" %(stop_time-start_time))
                    return res
            return wrapper
        return auth_func
    
    @auth(auth_type='filedb') #home = auth(auth_type='field') --> home = auth_func(home) --> home = wrapper
    def home(name):
        print("欢迎%s回家" %name)
    @auth(auth_type='ldap')
    def shopping():
        time.sleep(2)
        print("购物车里有:牛奶,面包,大米")
    home('zsz')
    shopping()

    输出结果为:

    认证方式是: filedb
    用户名:zsz
    密码:123
    欢迎zsz回家
    认证方式是: ldap
    购物车里有:牛奶,面包,大米
    函数运行时间为2.0004611015319824秒

  • 相关阅读:
    计网:传输层
    计网:网络层
    codeblocks 的安装与初体验
    二叉排序树的建立
    使用颜色空间进行图像分割
    密码学笔记
    Git笔记
    SVM笔记
    GAN笔记——理论与实现
    leetcode(三)
  • 原文地址:https://www.cnblogs.com/zhangsenzhen/p/9392258.html
Copyright © 2020-2023  润新知