1. 程式人生 > >python 中 裝飾器

python 中 裝飾器

裝飾器

 裝飾器的本質:一個閉包函式

  裝飾器的功能:在不修改原函式及其呼叫方式的情況下對原函式功能進行擴充套件

修飾器詳解請看:點選連結

(1)程式碼:外部的 f1 函式函式被徹底隱藏

程式碼:

def f1(x):
    return x*2
def new_fn(f):    #裝飾器函式
    def ff(x):
        print("call" + f.__name__ + "()")
        return f(x)
    return ff
g = new_fn(f1)
print(g(5))
f1 = new_fn(f1)
print(f1(5))
#外部的 f1 函式函式被徹底隱藏

結果:

(2)有必加值時

  程式碼:

import time
from functools import reduce
def performance(tt):              # 當有必加的數值 或 字串時 可以這樣寫 如必加字元 DEBUG
    def d_performance(f):         # 裝飾器函式
       def fa(*args, **kw):       #接受多個引數,但知道幾個引數時,可以不用最上面那個函式,
           star = time.time()     #裝飾器本身不就是更改新增 python一些內建函式的模組中的函式中的一些功能嗎
           l = f(*args,**kw)
           end = time.time()
           print("[%s]call %s() in %f s" % (tt,f.__name__,(end-star)))
           return l
       return fa
    return d_performance
@performance('DEBUG')
def factorial(n):
    return reduce(lambda x,y: x*y, range(1, n+1))
print (factorial(10))

(3)若裝飾之後,不該不變原函式的屬性、

  請看程式碼:

import time,functools
from functools import reduce
def performance(tt):
    def d_performance(f):
       @functools.wraps(f)   # 這一步為了不改變裝飾過的factorial函式的屬性,若不加上一步,你在下面輸出
       def fa(*args, **kw):  #factorial.__name__的屬性那麼是 fa,若加上這一步,那麼輸出的是factorial,大家可以動手試一下
           star = time.time()
           l = f(*args,**kw)
           end = time.time()
           print("[%s]call %s() in %f s" % (tt,f.__name__,(end-star)))
           return l
       return fa
    return d_performance
@performance('@decorator')
def factorial(n):
    return reduce(lambda x,y: x*y, range(1, n+1))
print (factorial(10))
print(factorial.__name__)

(1)偏函式的話:請看:點選1 或 點選2