zoukankan      html  css  js  c++  java
  • 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')
    
    

      

  • 相关阅读:
    bzoj3946
    bzoj3065
    bzoj1500
    bzoj1233
    bzoj1089
    bzoj1087
    bzoj1086
    if语句之猜拳
    if语句判断闰年、平年
    if语句判断身高体重是否标准
  • 原文地址:https://www.cnblogs.com/DLGD/p/7757746.html
Copyright © 2011-2022 走看看