13-Python-裝飾器

來源:互聯網
上載者:User

標籤:and   rand   原始碼   mil   擷取   分隔字元   sleep   soft   變數   

1、裝飾器的定義

裝飾器的本質就是函數,用來裝飾其它函數,就是為其它函數添加附加功能。

裝飾器原則如下:

  • 不能修改被裝飾的函數的原始碼
  • 不能修改被裝飾的函數的調用方式

2、實現裝飾器知識儲備

  • 函數即變數
 1 def bar(): 2     print("in the bar") 3 def foo(): 4     print("in the foo") 5     bar() 6  7 foo() 8  9 print("----------分割線-----------")10 11 def foo1():12     print("in the foo")13     bar1()14 def bar1():15     print("in the bar")16 17 foo1()18 19 print("----------分割線-----------")20 # 這樣會報錯21 # def foo2():22 #     print("in the foo")23 #     bar2()24 # foo2()25 # def bar2():26 #     print("in the bar")

 

  • 高階函數
  • 把一個函數名當作實參傳遞給另外一個函數(在不修改被裝飾函數原始碼的情況下為其添加功能)
 1 import time 2  3 def bar1(): 4     time.sleep(3) 5     print("in the bar") 6  7 def test2(func): 8     start_time = time.time() 9     func()  # 相當於運行bar1()10     stop_time = time.time()11     print("total run time %s" %(stop_time - start_time))12 13 test2(bar1)  

 

  • 傳回值中包含函數名(不能修改函數的調用方式)
 1 def bar2(): 2     time.sleep(3) 3     print("in the bar2") 4  5 def test3(func): 6     print(func) 7     return func 8  9 print(test3(bar2))  # 擷取的是記憶體位址10 11 res = test3(bar2)12 res()

 

  • 嵌套函數
1 def foo():2     print("in the foo")3     def bar():4         print("in the bar")5     bar()  # 局部變數只能在其範圍內調用6 7 foo()
 1 x = 0 2 def grandpa(): 3     x = 1 4     def dad(): 5         x = 2 6         def son(): 7             x = 3 8             print(x)  # 最終列印結果為3 9         son()10     dad()11 grandpa()

 

  • 高階函數 + 嵌套函數 --》裝飾器
 1 import time 2  3  4 def timer(func): 5     def deco(): 6         start_time = time.time() 7         func() 8         stop_time = time.time() 9         print("total time is %s" % (stop_time - start_time))10     return deco  # 返回deco()的記憶體位址11 12 13 def test1():14     time.sleep(3)15     print("in the test1")16 17 18 def test2():19     time.sleep(3)20     print("in the test2")21 22 23 timer(test1)  # test1的記憶體位址賦值給func,返回deco()的記憶體位址24 print(timer(test1))  # 返回deco()的記憶體位址25 test1 = timer(test1)  # 記憶體位址賦值給test126 test1()  # 相當於執行deco()27 28 timer(test2)29 test2 = timer(test2)30 test2()31 32 print("---------我是分隔字元---------")33 34 35 # 裝飾器文法如下36 @timer  # 相當於test1 = timer(test1)37 def test1():38     time.sleep(3)39     print("in the test1")40 41 42 @timer43 def test2():44     time.sleep(3)45     print("in the test2")46 47 48 test1()49 test2()

 

 

13-Python-裝飾器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.