4、装饰器、生成器、迭代器

装饰器

在函数前后做点事情,比如鉴权、记录日志

将执行的函数传入包装函数,在包装函数内部使用闭包构造包含传入函数的新函数,返回新函数,执行的函数指向新函数

函数编程的开闭原则:对添加开放,对修改关闭

def wrap1(fun):
    def inFun(*listargs,**dictargs):
        token = dictargs.pop('token')#获取token,并删除,等价于先取值,再del dictargs['token']
        is_login = False
        if not is_login:
            return "非法用户"
        print 1
        temp = fun(*listargs,**dictargs)
        print 2
        return temp
    return inFun
def wrap2(fun):
    def inFun(*listargs,**dictargs):#动态参数获取参数
        print 3
        temp = fun(*listargs,**dictargs)#fun指向传入的原f1的函数体
        print 4
        return temp
    return inFun


@wrap1
@wrap2#先包装wrap2,再包装wrap1,等价于f1 = wrap(f1);f1指向新函数
def f1(arg):
    print "f1%s" % arg
    return ['1.1.1.1']

print f1('haha')

  

posted @ 2017-11-09 12:04  dlgd  阅读(103)  评论(0编辑  收藏  举报