Python連載19-裝飾器

1、檢視一個函數相同的另外一種方法python

利用屬性:函數._namegit

def hello():
  print("我是一個測試程序")
f = hello
print(f.__name__)
print(hello.__name__)

從結果來看他們的本體都是hello函數github

2、裝飾器微信

1.定義:在不改動代碼的基礎上無限擴展函數功能的一種機制,本質上來說,裝飾器是一個返回函數的高階函數。app

2.裝飾器的使用:使用@愈發,即在每次要擴展到函數定義前使用@+函數名。函數

import time
#對hello函數進行功能擴展,每次執行hello前打印時間
def printTime(f):
# 高階函數,以函數做爲參數
  def wrapper(*args,**kwargs):
    print("Time:",time.ctime())
    return f(*args,**kwargs)
  return wrapper
#上面定義了裝飾器,使用的時候須要用到@符號,此符號是python語法
@printTime
def hello():
  print("Hello World")
hello()


3.裝飾器的好處:學習

(1)裝飾器的好處是,一旦定義,則能夠裝飾任意函數
(2)一旦被其裝飾,則把裝飾器的功能直接添加在定義函數的功能上測試

4.上面對函數的裝飾使用了系統定義的語法糖,下面開始手動執行一下裝飾器大數據

.......複用了上面的代碼........
def hello3():
  print("厲害")
hello3 = printTime(hello3)
#這是向printTime傳參hello3,而後返回wrapper,也就是hello3 = wrapper
hello3()
#執行了hello3函數,也就是執行了wrapper函數,先打印了「厲害」而後返回了最開始的hello3,可是後面有括號就是執行了最開始的
#hello3(),打印了厲害


5.遺留問題:ui

aa = printTime(hello3)
aa()

爲何出來了兩個時間戳

 

3、源碼:

d20_3_wrapper

地址:https://github.com/ruigege66/Python_learning/blob/master/d20_3_wrapper

2.CSDN:https://blog.csdn.net/weixin_44630050(心悅君兮君不知-睿)

3.博客園:https://www.cnblogs.com/ruigege0000/

4.歡迎關注微信公衆號:傅里葉變換,後臺回覆」禮包「,獲取大數據學習資料

相關文章
相關標籤/搜索