装饰器基本概念及示例

装饰器本身是一个函数

@ :语法糖

装饰器原则:

 1,不改变函数原代码

 2,不改变函数调用方式

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

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

#定义一个验证用户名密码的装饰器
user_list=[
    {'name':'zhuo','passwd':'123'},
    {'name':'sen','passwd':'123'},
    {'name':'wbin','passwd':'123'},
    {'name':'wu','passwd':'123'},
]
current_dic = {'username':None,'login':False}

def auth_func(func):
    def warpper(*args,**kwargs):
        if current_dic['username'] and current_dic['login']:
            res = func(*args,**kwargs)
            return res
        username = input('用户名:').strip()
        passwd = input('密码:').strip()
        for user in user_list:
            if user['name'] == username and user['passwd'] == passwd:
                current_dic['username'] = username
                current_dic['login'] = passwd
                #print(current_dic)
                res = func(*args,**kwargs)
                return res
        else:
            print('用户名或密码错误')
    return warpper
@auth_func
def index():
    print('欢迎来到主页')
@auth_func
def home(name):
    print('欢迎来到家 %s'%name)
@auth_func
def shopping_car(*args):
    print('购物车里面有 %s %s %s'%('电脑','手机','平板'))

index()
home('zhuo')
shopping_car()

 

posted on 2018-02-23 18:24  卓某  阅读(111)  评论(0编辑  收藏  举报

导航