国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python中裝飾器學習總結

2020-02-22 23:11:32
字體:
來源:轉載
供稿:網友

本文研究的主要內容是Python中裝飾器相關學習總結,具體如下。

裝飾器(decorator)功能

引入日志 函數執行時間統計 執行函數前預備處理 執行函數后清理功能 權限校驗等場景 緩存

裝飾器示例

例1:無參數的函數

from time import ctime, sleepdef timefun(func): def wrappedfunc():  print("%s called at %s"%(func.__name__, ctime()))  func() return wrappedfunc@timefundef foo(): print("I am foo")foo()sleep(2)foo()

分析如下:

上面代碼理解裝飾器執行行為可理解成

foo = timefun(foo)

1,foo先作為參數賦值給func后,foo接收指向timefun返回的wrappedfunc
2,調用foo(),即等價調用wrappedfunc()
3,內部函數wrappedfunc被引用,所以外部函數的func變量(自由變量)并沒有釋放
4,func里保存的是原foo函數對象

例2:被裝飾的函數有參數

from time import ctime, sleepdef timefun(func): def wrappedfunc(a, b):  print("%s called at %s"%(func.__name__, ctime()))  print(a, b)  func(a, b) return wrappedfunc@timefundef foo(a, b): print(a+b)foo(3,5)sleep(2)foo(2,4)

例3:被裝飾的函數有不定長參數

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

例4:裝飾器中的return

from time import ctime, sleepdef timefun(func): def wrappedfunc():  print("%s called at %s"%(func.__name__, ctime()))  func() return wrappedfunc@timefundef foo(): print("I am foo")@timefundef getInfo(): return '----hahah---'foo()sleep(2)foo()print(getInfo())

執行結果:

foo called at Sun Jun 18 00:31:53 2017
I am foo
foo called at Sun Jun 18 00:31:55 2017
I am foo
getInfo called at Sun Jun 18 00:31:55 2017
None

如果修改裝飾器為return func(),則運行結果:

foo called at Sun Jun 18 00:34:12 2017
I am foo
foo called at Sun Jun 18 00:34:14 2017
I am foo
getInfo called at Sun Jun 18 00:34:14 2017
----hahah---

小結:一般情況下為了讓裝飾器更通用,可以有return

例5:裝飾器帶參數,在原有裝飾器的基礎上,設置外部變量

from time import ctime, sleepdef 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("itcast")def foo(): print("I am foo")@timefun_arg("python")def too(): print("I am too")foo()sleep(2)foo()too()sleep(2)too()可以理解為foo()==timefun_arg("itcast")(foo)()            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 盈江县| 西乌| 钟山县| 政和县| 嘉禾县| 亚东县| 建德市| 厦门市| 隆昌县| 呈贡县| 平谷区| 崇文区| 洪洞县| 东丽区| 新丰县| 安阳县| 隆化县| 宁波市| 呼伦贝尔市| 莱芜市| 石泉县| 铜梁县| 新干县| 南康市| 本溪市| 南丰县| 峨眉山市| 麻江县| 陆河县| 泸西县| 克拉玛依市| 华安县| 龙陵县| 磴口县| 夏河县| 琼中| 宜阳县| 城市| 谷城县| 白银市| 贺兰县|