• 装饰器


    #装饰器的基本理论:
    #装饰器本质就是函数,目的是为函数增加新的功能
    #使用原则:
    #不修改被修饰函数的源代码
    #不修改被修饰函数的调用方式
    #装饰器=高阶函数+闭包+函数嵌套
    #高阶函数:
    #定义:函数接收的参数是一个函数名;函数的返回值是一个函数名。满足其中一个就是高阶函数


    #装饰器框架:
    '''
    def timmer(func): #test=func
    def wrapper():
    print('------------>添加新功能开始的位置')
    print(func) #输出func的地址
    func() #执行func,即执行test
    print('------------>新功能添加结束的位置')
    return wrapper
    @timmer
    def test():
    print('来自test')
    test()
    '''

    #1)比如:为下面的函数添加,检查函数运行时间的功能
    import time
    def Time(func):
    def wrapper():
    start_time = time.time() #起始时间
    func()
    stop_time = time.time() #结束时间
    x = (stop_time - start_time)
    print('Foo函数的运行时间是%s' %round(x,2)) #利用round函数保留两位小数
    return wrapper
    @Time
    def Foo():
    info = {}
    info.update(key1=1, key2=2, key3=3)
    for k, v in info.items(): # 利用items()函数输出键值对
    time.sleep(0.1)
    print(k, v)
    Foo = Time(Foo) #返回的是wrapper的地址 ,等价于在要添加功能的函数前面加上@timmer(@装饰器名)
    Foo() #执行wrapper

    #2)为装饰器加上返回值,原函数才可加上返回值
    import time
    def Time(func):
    def wrapper():
    start_time = time.time()
    res = func()
    stop_tme = time.time()
    x = stop_tme - start_time
    print('函数的执行时间为:%s'%round(x,2))
    return res
    return wrapper
    @Time
    def test():
    info = {}
    info.update(a=1,b=2,c=3)
    for key,val in info.items():
    time.sleep(0.1)
    print(key,val)
    print('test运行结束')
    return info
    print(test())

    #3)为装饰器加上参数
    import time
    def Time(func):
    def wrapper(*args ,**kwargs):
    start_time = time.time()
    res = func(*args ,**kwargs)
    stop_time = time.time()
    x= stop_time - start_time
    print('函数的运行时间为:%s'%round(x,2))
    return res
    return wrapper
    @Time
    def test(name,age):
    info = {}
    info.update(name=name,age=age) #为字典添加内容
    for key,val in info.items(): #遍历字典
    time.sleep(0.1)
    print(key,val)
    return info #返回字典
    ret = test('alex',21)
    print(ret)
    print('---------------------------->')
    @Time
    def test_2(name,age,gender): #三个参数
    time.sleep(2)
    print("test_1结束,name=%s,age=%s,gender=%s"%(name,age,gender))
    return '这是test_2的返回值'
    ret_2 = test_2('小李',11,'')
    print(ret_2)

    #4)为函数加上认证功能
    def auth_func(func):
    def wrapper(*args ,**kwargs ):
    username = input('用户名:').strip()
    passwd = input('密 码:').strip()
    if username == '' and passwd == '':
    res = func(*args ,**kwargs )
    return res
    else:
    print('用户名/密码错误')
    return wrapper
    @auth_func
    def test(name,age):
    info = {}
    info.update(name=name,age=age)
    return info
    ret = test('alex',15)
    print(ret)

    #5)函数闭包模拟验证功能装饰器
    user_list = [
    {'name':'alex','passwd':'1'},
    {'name':'alo','passwd':'2'},
    ]
    current_dic = {'username':None,'login':False}

    def auth_c(func):
    def wrapper(*args ,**kwargs ):
    #默认passwd
    if current_dic['username'] and current_dic ['login']:
    res = func(*args ,**kwargs )
    return res
    username = input('用户名:').strip()
    passwd = input('密 码:').strip()
    for user_dic in user_list :
    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('Error:usename/passwd')
    return wrapper

    @auth_c
    def index():
    print('欢迎来到index')
    def home():
    pass
    index()

    #6)带参数的验证功能装饰器
    user_list = [
    {'name':'alex','passwd':'123'},
    {'name':'xiaoli','passwd':'123'}
    ]
    current_dict = {'username':None,'login':False}
    def auth(auth_type = 'filed'):
    def auth_decp(func):
    def wrapper(*args ,**kwargs ):
    print('认证类型是',auth_type )
    if auth_type == 'filed':
    if current_dict['username'] and current_dict['login']:
    ret = func(*args,**kwargs)
    return ret
    username = input('用户名:').strip()
    passwd = input('密码:').strip()
    for user_dict in user_list :
    if username == user_dict['name'] and passwd == user_dict['passwd']:
    current_dict ['username'] = username
    current_dict ['login'] = True
    ret = func(*args ,**kwargs )
    return ret
    else:
    print('用户名或密码错误')
    return wrapper
    return auth_decp

    @auth(auth_type = 'filed')
    def index():
    print('欢迎来到主页面')

    index()
  • 相关阅读:
    $P5240 Derivation$
    $P2504 [HAOI2006]聪明的猴子$
    $P1194 买礼物$
    $P2690 接苹果$
    $CF1141C Polycarp Restores Permutation$
    $CF1141B Maximal Continuous Rest$
    $CF1141A Game 23$
    $P1215 [USACO1.4]母亲的牛奶 Mother's Milk$
    $luogu2375[NOI2014]$
    poj 1419 (最大独立集)
  • 原文地址:https://www.cnblogs.com/shadowfolk/p/14590498.html
Copyright © 2020-2023  润新知