python 装饰器 传递参数简单案例

def debug(func):python

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

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

    print 'Prepare and say...',函数

         return func(*args, **kwargs)this

 return wrapper # 返回debug

@debugcode

def say(something):orm

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

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

 

我本身的例子

#!/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 -- 至关于字典

用一个例子来演示会更加清晰
相关文章
相关标签/搜索