zoukankan      html  css  js  c++  java
  • 函数闭包带参数装饰器

    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秒

  • 相关阅读:
    skill:极角排序
    skill:树的重心
    [CF1091F](New Year and the Mallard Expedition)
    2018九省联考(SHOI2018)
    陷入僵局?
    2333
    雨后天晴
    听说我首次抢到食堂最早的馄饨
    难题做不动
    成绩出来了?
  • 原文地址:https://www.cnblogs.com/zhangsenzhen/p/9392258.html
Copyright © 2011-2022 走看看