1. 程式人生 > >python 裝飾器詳解

python 裝飾器詳解

不定 返回 緩存 特性 mef ali int 感受 cti

裝飾器

裝飾器其實就是一個閉包,把一個函數當做參數然後返回一個替代版函數

裝飾器有2個特性:

一是可以把被裝飾的函數替換成其他函數, 

二是可以在加載模塊時候立即執行

def w1(func):

  def inner():

     # 驗證1

    # 驗證2

     # 驗證3  

     func()

  return inner

@w1

def f1():

print(‘f1‘)

裝飾器(decorator)功能

1. 引??誌

2. 函數執?時間統計

3. 執?函數前預備處理

4. 執?函數後清理功能

5. 權限校驗等場景

6. 緩存

上代碼直觀感受

#定義函數: 完成包裹數據
def makeBold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped

@makeBold
def test1():
return "hello world-1"
#定義函數: 完成包裹數據
def makeItalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped

@makeItalic
def test2():
return "hello world-2"

@makeBold
@makeItalic
def test3():
return "hello world-3"

print(test1())
print(test2())
print(test3())

裝飾器對無參函數進行裝飾
from time import ctime, sleep
def timefun(func):
def wrappedfunc():
print("%s called at %s"%(func.__name__, ctime()))
func()
return wrappedfunc
@timefun
def foo():
print("I am foo")
foo()
sleep(2)
foo()

裝飾器對有參函數進行裝飾

from time import ctime, sleep

def timefun(func):

  def wrappedfunc(a, b):

    print("%s called at %s"%(func.__name__, ctime()))

    print(a, b)

     func(a, b)

   return wrappedfunc

@timefun

def foo(a, b):

   print(a+b)

foo(3,5)

sleep(2)

foo(2,4)

裝飾器對不定長參數函數進行裝飾

from time import ctime, sleep

def timefun(func):

  def wrappedfunc(*args, **kwargs):

    print("%s called at %s"%(func.__name__, ctime()))

     func(*args, **kwargs)

   return wrappedfunc

@timefun

def foo(a, b, c):

   print(a+b+c)

foo(3,5,7)

sleep(2)

foo(2,4,9)

裝飾器對帶有返回值的函數進行裝飾

from time import ctime, sleep

def timefun(func):

  def wrappedfunc(*args, **kwargs):

    print("%s called at %s"%(func.__name__, ctime()))

     ret = func()

    return ret

   return wrappedfunc

@timefun

def foo():

  print("I am foo")

@timefun

def getInfo():

return ‘----hahah---‘

帶有參數的裝飾器

from time import ctime, sleep

def timefun_arg(pre="hello"):

  def timefun(func):

  def wrappedfunc():

    print("%s called at %s %s"%(func.__name__, ctime(), pre))

     return func()

    return wrappedfunc

  return timefun

@timefun_arg(“sxt")

def foo():

  print("I am foo")

@timefun_arg("python")

def too():

  print("I am too" )

from time import ctime, sleep def timefun(func): def wrappedfunc(*args, **kwargs): print("%s called at %s"%(func.__name__, ctime())) func(*args, **kwargs) return wrappedfunc @timefun def foo(a, b, c): print(a+b+c) foo(3,5,7) sleep(2) foo(2,4,9)

python 裝飾器詳解