Python 自定義裝飾器與函式的可變引數
阿新 • • 發佈:2018-12-14
1.函式的可變引數
def f(*args, **kw):
*:代指元組,長度不限
**:代表鍵值對,個數不限
def f(*args, **kw):
print len(args)
print args
for i in kw:
print i:kw[i]
f(1,a,2,name='wu', age=111)
#輸出:
'''
3
1,a,2
name=wu
age=111
'''
2.自定義裝飾器
讓函式作為裝飾器函式的引數,達到裝飾函式的效果(函式命名隨意)
來分析這個式子, 可以看出至少要滿足以下幾個條件 1. 裝飾器函式執行在函式定義的時候 2. 裝飾器需要返回一個可執行的物件 3. 裝飾器返回的可執行物件要相容函式f的引數
import time def decorator(max): def _decorator(fun): def wrapper(*args, **kwargs): start = time.time() for i in xrange(max): fun(*args, **kwargs) runtime = time.time()-start print runtime return wrapper return _decorator # 迴圈f()函式兩次 @decorator(2) def do_something(name): for i in range(1000000): pass print "play game " + name do_something("san guo sha") --------------------- #本文來自 TangHuanan 的CSDN 部落格 ,全文地址請點選:#https://blog.csdn.net/TangHuanan/article/details/45094497?utm_source=copy