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 -- 至關於字典

用一個例子來演示會更加清晰
相關文章
相關標籤/搜索