zoukankan      html  css  js  c++  java
  • python 装饰器 传递参数简单案例

    def debug(func):

         def wrapper(*args, **kwargs): # 指定宇宙无敌参数

        print "[DEBUG]: enter {}()".format(func.__name__)

        print 'Prepare and say...',

             return func(*args, **kwargs)

     return wrapper # 返回

    @debug

    def say(something):

      print "hello {}!".format(something)

    Python提供了可变参数*args和关键字参数**kwargs,有了这两个参数,装饰器就可以用于任意目标函数了。

    参考:https://www.cnblogs.com/cicaday/p/python-decorator.html

    我自己的例子

    #!/usr/bin/env python
    #todo use decorator to decorate the function that need debug and its function name
    def debug(f):
      def wrapper(*args,**kwargs):
        print("this is the name of function: {0}".format(f.__name__))
        if kwargs['username'] != 'admin':
          raise Exception('you need to be admin') 
        f(*args,**kwargs) #装饰器内部函数的参数等于被修饰函数的参数
      return wrapper


    @debug
    def say_hi(sth,username):

      print("this is position args {0}".format(sth))
      print("i am the master: {0}".format(username))
    if __name__ == '__main__':
      say_hi('first args',username='admin')
      say_hi('first args',username='haha')

    *args  -- 相当于 列表   **kwargs -- 相当于字典

  • 相关阅读:
    用java代码调用shell脚本执行sqoop将hive表中数据导出到mysql
    用sqoop将mysql的数据导入到hive表中
    windows下启动mysql服务的命令行启动和手动启动方法
    使sqoop能够启用压缩的一些配置
    简易安装sqoop
    sqoop一些语法的使用
    mysql 视图
    MySQL 函数大全及用法示例
    MySQL 触发器 -1
    MySQL 函数
  • 原文地址:https://www.cnblogs.com/hixiaowei/p/9049764.html
Copyright © 2011-2022 走看看