本來寫了一個函數:app
def say_hello(data): print("hello {0}" .format(data))
領導要求在每一個函數打印的時候加上說明:「debug : xxx say_hello()」函數
方法一:spa
粗暴一點的方法是直接拿出來寫一個函數,每次都調用它:這種方法也能夠實現,要是有100個函數要添加呢,萬一又有一部分函數不須要了呢?維護起來有點噁心debug
def func(fp): print("debug : xxx {0}()" .format(fp.__name__)) def say_goodbay(): func(say_goodbay) print("baybay") say_goodbay()
方法二:使用裝飾器,這種方法不改變原代碼 *args,**kwargscode
def add_values(func): def wrapper(*args,**kwargs): print("debug : xxx {0}()" .format(func.__name__)) return func(*args,**kwargs) return wrapper @add_values def say_hello(data): print("hello {0}" .format(data)) say_hello('alibaba')