關於python中裝飾器的一些小見解

最近在學習python3,對於python的裝飾器,多線程以及異步IO有點卡頓。這兩天在研究python的裝飾器,之前在看廖雪峰大神的裝飾器感覺一臉懵逼。轉而去看伯樂在線的裝飾器教程,這裡不是做廣告。伯樂在線的確解決挺多疑惑。仔細閱讀了很多作者的裝飾器教程,特此做個總結來加深對python的裝飾器的瞭解。

關於python中裝飾器的一些小見解

函數

  • 在python當中函數也是可以直接作為函數參數傳給另外一個函數。在這種情況,函數也是作為一個變量,例如:

def now(func): func()def hello(): print("hello world")now(hello)#直接輸出 hello world

作用域

  • python函數內部定義變量,我們稱為局部變量,有人稱為命名空間。python作用域與javascript的作用域相似。函數內部定義的變量,函數外不能直接訪問(全局作用域下);如果全局作用域下與函數作用域存在同名變量,函數會優先使用函數內部變量值;若函數內部不存在這個變量,則解釋器會一層層往上訪問直至全局作用域(如果不存在,則拋出錯誤)。

1. def func(): name="kiwis" print("my name is %s"%name) func()# python shell環境1輸出 my name is kiwis
2.name ="DB"def func(): name="kiwis" print("my name is %s"%name)func()# python shell環境1輸出 my name is kiwis
3.name ="DB"def func(): print("my name is %s"%name)func()# python shell環境1輸出 my name is DB

裝飾器

  • 裝飾器到底是什麼?為什麼要使用裝飾器?裝飾器顧名思義就是錦上添花,裝飾,為原有事物添加更好的東西。如果我們在初期定義了一個函數;但是突然之間想要知道這個函數執行了多長時間;但是又不用修改原有函數,這個時候python裝飾器派上用場。示例如下:

from datetime import datetimedef logtime(func): def runFun(*args,**kwargs): print("the start time is %s"%datetime.now()) res=func(*args, **kwargs) print("the end time is %s"% datetime.now()) return res return runFun()def add(): print("hello world")add=logtime(add())
  • 上面add=logtime(add())在python中提供了用@標識符來表示裝飾器的語法糖,用@表示的語法其實和上面最後一句作用是一樣的。示例代碼如下:

from datetime import datetimedef logtime(func): def runFun(*args,**kwargs): print("the start time is %s"%datetime.now()) res=func(*args, **kwargs) print("the end time is %s"% datetime.now()) return res return runFun()@logtimedef add(): print("hello world")
  • 在使用python裝飾器時,裝飾器函數返回一個函數runFun,此時add函數的name值已經不是add了,如果要改變成原來的相關變量,python中提供了functools.wrap()幫助我們完成。

from datetime import datetimedef logtime(func): @functools.wrap(func) def runFun(*args,**kwargs): print("the start time is %s"%datetime.now()) res=func(*args, **kwargs) print("the end time is %s"% datetime.now()) return res return runFun()@logtimedef add(): print("hello world")

python裝飾器有針對函數的裝飾器和對象的裝飾器。下次繼續闡述一下面對對象的裝飾器。

相關推薦

推薦中...