Python从入门到精通:Python装饰器详解
生活随笔
收集整理的這篇文章主要介紹了
Python从入门到精通:Python装饰器详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
裝飾器本質就是函數,作用是裝飾其它函數,給其它函數增加附加功能,提高代碼復用,減少代碼量。
我們平時給函數增加新的功能時,通過修改此函數或在函數里調用新的函數實現,但是1、如果這個函數已經是上線的功能,這時修改程序原代碼有很大風險 2、如果有100個這樣的函數,我們就要找到100個地方進行修改。
例如:我們想新增功能,驗證函數執行了多長時間,代碼如下:
#修改原函數
裝飾器原則:
1、不能修改被裝飾函數的源代碼
2、不能修改被裝飾函數的調用方式
實現裝飾器儲備知識:
高階函數+嵌套函數=裝飾器
1、函數即變量
2、高階函數
a:把一個函數名當做實參傳給另外一個函數(在不修改被裝飾函數源代碼的情況下為其添加功能)
b:返回值中包含函數名
滿足a或b就是高階函數
3、嵌套函數
def foo():print('in the foo')def bar():print('in the bar')bar() foo()"C:\Program Files\Python35\python.exe" C:/Users/wangli/PycharmProjects/Test/Test/test.py in the foo in the barProcess finished with exit code 0不帶參數的裝飾器:
import time def timer(func):def deco():start_time=time.time()func()stop_time=time.time()print('the func run time is %s'%(stop_time-start_time))return deco @timer #test1=timer(test1) def test1():time.sleep(3)print('in the test1') test1()"C:\Program Files\Python35\python.exe" C:/Users/wangli/PycharmProjects/Test/Test/test.py in the test1 the func run time is 3.000833511352539Process finished with exit code 0帶參數的裝飾器:
從實:1中看出@timer相當于test2=timer(test2),timer(func)中func傳的是test2,故func=test2
timer(test2)=deco,因為test2=timer(test2),故test2=deco=func
test2(name,age)=deco(name,age)=func(name,age)所以傳參到deco和func里
實例1:
實例2:
import timedef timmer(flag):""":param flag: 接收裝飾器的參數:return:"""def outer_wrapper(func):""":param func: 接收被裝飾的函數:return:"""# 接收被裝飾函數的參數def wrapper(*args, **kwargs):""":param args: 收集被裝飾函數的參數:param kwargs: 收集被裝飾函數的關鍵字參數:return:"""if flag == "true":start_time = time.time()# 調用被裝飾的函數result = func(*args, **kwargs)# 讓進程睡一秒time.sleep(1)stop_time = time.time()print("{func} spend {time} ".format(func="add", time=stop_time - start_time))return resultelse:print("Unexpected ending")return wrapperreturn outer_wrapper總結
以上是生活随笔為你收集整理的Python从入门到精通:Python装饰器详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 面试:数据分析面试SQL操作真题解析
- 下一篇: 对比excel,用python绘制柱状图