Python3 函數裝飾器(002)

在不改變函數的情況下,給其增加一些額外的代碼

#功能代碼與業務邏輯分開def sentM(): print(發圖片)def sentW(): print(發文字)btn = 2if btn == 1: sentM()else: sentW()

增加額外代碼

def checklogin(func): def inner(): print(檢查輸入......) func() return innerdef sentM(): print(發圖片)sentM = checklogin(sentM)def sentW(): print(發文字)sentW = checklogin(sentW)btn = 1if btn == 1: sentM()else: sentW()============================================def checklogin(func): def inner(): print(檢查輸入......) func() return inner@checklogindef sentM(): print(發圖片)@checklogindef sentW(): print(發文字)btn = 2if btn == 1: sentM()else: sentW()--------------------------------------------->>> def now(): print(12:30) >>> f = now>>> f()12:30--------------------------------------------->>> def log(func): def wrapper(*arg, **kwarg): print(call %s(): % func.__name__) return func(*arg, **kwarg) return wrapper>>> @logdef now(): print(12:30) >>> now()call now():12:30-----------------------------------------------

推薦閱讀:

es7你都懂了嗎?今天帶你了解es7的神器decorator

TAG:Python3x | 函數式編程 | 裝飾器 |