day20

                                装饰器
装饰器本质就是函数, 为其他函数添加附加功能

# 原则:
# 1.不修改被修饰函数的源代码
# 2.不修改被修饰函数的调用方式

'''
高阶函数定义:
1.函数接收的参数是一个函数名
2.函数的返回值是一个函数名
3.满足上述条件任意一个,都可称之为高阶函数
'''
def foo():
    print('from the foo')

def test(func):
    return func

res=test(foo)
# print(res)
res()

函数的闭包    闭包包含函数嵌套

def father(auth_type):
    # print('from father %s' %name)
    def son():
        # name='xxxxx'
        # print('我的爸爸是%s' %name)
        def grandson():
            print('我的爷爷是%s' %auth_type)
        grandson()
    #print(locals())
    son()

father('filedb')

  

装饰器 =  高阶函数 + 函数嵌套 + 闭包

装饰器

 1.基本装饰器

import  time
def timmer(func):
    def wrapper():
        start_time = time.time()
        func()
        stop_time = time.time()
        print('运行时间是%s'%(stop_time - start_time))
    return wrapper

# def test():
#     time.sleep(1)
#     print('test函数执行完毕')
#
# test = timmer(test)    #返回的是wrapper的地址
# test()                 #执行的是wrapper()

@timmer   #test = timmer(test)
def test():
    time.sleep(1)
    print('test函数执行完毕')

test()

#结果:test函数执行完毕
#      运行时间是1.0080018043518066 


#  @timmer  就相当于 test=timmer(test)

 

2.加上返回值

import  time
def timmer(func):
    def wrapper():
        start_time = time.time()
        ret = func()
        stop_time = time.time()
        print('运行时间是%s'%(stop_time - start_time))
        return ret
    return wrapper


@timmer   #test = timmer(test)
def test():
    time.sleep(1)
    print('test函数执行完毕')
    return '1111111111'

rr = test()
print(rr)
#结果
'''
test函数执行完毕
运行时间是1.009007215499878
1111111111
'''

  3.加上参数

import  time
def timmer(func):
    def wrapper(name,age):
        start_time = time.time()
        ret = func(name,age)
        stop_time = time.time()
        print('运行时间是%s'%(stop_time - start_time))
        return ret
    return wrapper


@timmer   #test = timmer(test)
def test(name,age):
    time.sleep(1)
    print('名字是:%s 年纪是:%s'%(name,age))
    return '1111111111'

rr = test('yang',18)
print(rr)

#结果
'''
名字是:yang 年纪是:18
运行时间是1.0000061988830566
1111111111
'''

  

4.加多个参数  *args  **kwargs
import  time
def timmer(func):
    def wrapper(*args,**kwargs):
        start_time = time.time()
        ret = func(*args,**kwargs)
        stop_time = time.time()
        print('运行时间是%s'%(stop_time - start_time))
        return ret
    return wrapper


@timmer         #test = timmer(test)
def test(name,age,gender):
    time.sleep(1)
    print('名字是:%s 年纪是:%s 性别:%s'%(name,age,gender))
    #print(args)
    return '1111111111'

rr = test('yang',18,gender='nan')
print(rr)

# 结果
'''
名字是:yang 年纪是:18 性别:nan
运行时间是1.0010037422180176
1111111111
'''
 

  

 5.验证功能装饰器
 
user_list=[
    {'name':'alex','passwd':'123'},
    {'name':'linhaifeng','passwd':'123'},
    {'name':'wupeiqi','passwd':'123'},
    {'name':'yuanhao','passwd':'123'},
]
current_dic={'username':None,'login':False}

def auth_func(func):
    def wrapper(*args,**kwargs):
        if current_dic['username'] and current_dic['login']:
            ret = func(*args,**kwargs)
            return ret
        username = input('用户名:').strip()
        passwd = input('密码:').strip()
        for line in user_list:
            if username == line['name'] and passwd == line['passwd']:
                current_dic['username'] = username
                current_dic['login'] = True
                res = func(*args, **kwargs)
                return res
        else:
            print('账号或密码不对')
    return  wrapper


@auth_func
def index():
    print('欢迎来到京东主页')

@auth_func
def home(name):
    print('欢迎回家%s' %name)

@auth_func
def shopping_car(name):
    print('%s的购物车里有[%s,%s,%s]' %(name,'奶茶','妹妹','娃娃'))

index()
home('产品经理')
shopping_car('产品经理')
 

  6.带参数验证功能装饰器

 
user_list=[
    {'name':'alex','passwd':'123'},
    {'name':'linhaifeng','passwd':'123'},
    {'name':'wupeiqi','passwd':'123'},
    {'name':'yuanhao','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']:
                    ret = func(*args,**kwargs)
                    return ret
                username = input('用户名:').strip()
                passwd = input('密码:').strip()
                for line in user_list:
                    if username == line['name'] and passwd == line['passwd']:
                        current_dic['username'] = username
                        current_dic['login'] = True
                        res = func(*args, **kwargs)
                        return res
                else:
                    print('账号或密码不对')

            elif auth_type == 'ldap':
                print('鬼才特么会玩')
                res = func(*args, **kwargs)
                return res

            else:
                print('鬼才知道你用的什么认证方式')
                res = func(*args, **kwargs)
                return res


        return  wrapper
    return auth_func


@auth(auth_type='filedb')
def index():
    print('欢迎来到京东主页')

@auth(auth_type='ldap')
def home(name):
    print('欢迎回家%s' %name)

@auth(auth_type='sssssss')
def shopping_car(name):
    print('%s的购物车里有[%s,%s,%s]' %(name,'奶茶','妹妹','娃娃'))

index()
home('产品经理')
shopping_car('产品经理')
 

  

 

  

 

 





猜你喜欢

转载自www.cnblogs.com/augustyang/p/9050364.html