zoukankan      html  css  js  c++  java
  • 装饰器

    1、

    def log(func):   # 把函数传进来
      def wrapper(*args, **kvargs):    # *args,  无名字参数 。**kvargs  有名字参数
        print 'before calling', func.__name__
        print 'args', args, 'kvargs', kvargs
        func(*args, **kvargs)
        print 'end coding', func.__name__
      return wrapper

    @log   # 相当于log(hello((name, age))
    def hello(name, age):
      print 'hello',name, age


    if __name__ == '__main__':
      hello('nowcode', 2)

    结果:

    before calling hello
    args ('nowcode', 2) kvargs {}
    hello nowcode 2
    end coding hello

    若改为

    if __name__ == '__main__':
      hello(name = 'nowcode', age = 2)

    结果为:

    before calling hello
    args () kvargs {'age': 2, 'name': 'nowcode'}
    hello nowcode 2
    end coding hello

    2、带有参数的装饰器

    def log(level,*args, **kvargs):   #处理参数
      def inner(func):  # 把函数传进来
        def wrapper(*args, **kvargs):
          print level,'before calling', func.__name__
          print level,'args', args, 'kvargs', kvargs
          func(*args, **kvargs)
          print 'end coding', func.__name__
        return wrapper
      return inner

    @log(level='INFO')
    def hello(name, age):
      print 'hello',name, age


    if __name__ == '__main__':
      hello(name = 'nowcode', age = 2)

    输出为:

    INFO before calling hello
    INFO args () kvargs {'age': 2, 'name': 'nowcode'}
    hello nowcode 2
    end coding hello

  • 相关阅读:
    Python基础教程:多线程运行带多个参数的函数
    Python基础教程:list相关操作
    python字典教程:setdefault方法和get方法
    Python 异常处理集合
    python基础教程:5个带key的python内置函数
    python操作Excel的5种方式
    Python3压缩和解压缩实现
    jenkins 分布式配置主从节点
    CentOS7 free字段含义
    nginx配置https
  • 原文地址:https://www.cnblogs.com/toudoubao/p/6705850.html
Copyright © 2011-2022 走看看