Python 裝飾器(一)
Python 裝飾器(一)
首先,看一下下面三個函式,假如說我現在要加一個條件,計算每個函式所花費時間。
def add(x, y):
return x+y
def sub(x,y):
return x-y
def multi(x,y):
return x+y
如果不考慮效率,我們可以每個函式逐一新增如下:
import time
def add(x, y):
t1 = time.time()
s = x+y
time.sleep(3)
t2 = time.time()
times = str(t2 - t1)
print "spend : " + times + "s"
return s
def sub(x,y):
return x-y
def multi(x,y):
return x*y
if __name__ == "__main__":
sum = add(3, 4)
print sum
執行結果如下:
spend : 3.0s
7
如果有很多這樣的函式,我們不可能逐一的新增,那麼下面我們該如何處理呢?
這時候就該使用python 裝飾器了!
程式碼如下:
import time
def calc(fn):
def sum(x, y):
t1 = time.time()
s = fn(x, y)
time.sleep(3)
t2 = time.time()
times = str(t2 - t1)
print "spend : " + times + "s"
return s
return sum
@calc
def add(x,y):
return x + y
@calc
def sub(x,y):
return x-y
@calc
def multi(x,y):
return x*y
if __name__ == "__main__":
print add.__name__
print sub.__name__
print multi.__name__
a = add(3, 4)
b = sub(3,4)
c = multi(3,4)
print a,b,c
執行結果如下:
sum
sum
sum
spend : 3.0s
spend : 3.0s
spend : 3.0s
7 -1 7
通過上述程式碼引用,我們可以直觀的看出來,
裝飾器可以在不修改原有程式碼的基礎上,對已有同型別的一些函式 進行額外的補充!!
相關文章
- python裝飾器2:類裝飾器Python
- Python 裝飾器Python
- Python裝飾器Python
- 1.5.3 Python裝飾器Python
- python的裝飾器Python
- Python 裝飾器原理Python
- Python裝飾器模式Python模式
- 談一談Python中的裝飾器Python
- Python深入05 裝飾器Python
- python 之裝飾器(decorator)Python
- Python中的裝飾器Python
- Python裝飾器詳解Python
- python裝飾器入門探究Python
- python 裝飾器 part2Python
- day11(python)裝飾器Python
- python中裝飾器的原理Python
- Python裝飾器高階用法Python
- python 裝飾器小白學習Python
- 【python】閉包與裝飾器Python
- Python裝飾器的前世今生Python
- python的裝飾器@的用法Python
- Python深入分享之裝飾器Python
- Python 語法之裝飾器Python
- Python3 裝飾器解析Python
- Python閉包與裝飾器Python
- Python之函式裝飾器Python函式
- Python 裝飾器簡單示例Python
- python裝飾器有哪些作用Python
- python裝飾器是什麼Python
- 粗淺聊聊Python裝飾器Python
- 我終於弄懂了Python的裝飾器(一)Python
- 關於 Python 裝飾器的一些理解Python
- Python迭代器&生成器&裝飾器Python
- python幾種裝飾器的用法Python
- Python學習筆記 - 裝飾器Python筆記
- Python 裝飾器你也會用Python
- Python:從閉包到裝飾器Python
- python中的裝飾器介紹Python