溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在Python中使用函數(shù)裝飾器

發(fā)布時間:2021-05-14 16:10:25 來源:億速云 閱讀:135 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章給大家分享的是有關(guān)如何在Python中使用函數(shù)裝飾器,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

一、裝飾器

首先,我們要了解到什么是開放封閉式原則?

軟件一旦上線后,對修改源代碼是封閉的,對功能的擴(kuò)張是開放的,所以我們應(yīng)該遵循開放封閉的原則。

也就是說:我們必須找到一種解決方案,能夠在不修改一個功能源代碼以及調(diào)用方式的前提下,為其加上新功能。

總結(jié):原則如下:

1、不修改源代碼
2、不修改調(diào)用方式

目的:在遵循1和2原則的基礎(chǔ)上擴(kuò)展新功能。

二、什么是裝飾器?

器:指的是工具,

裝飾:指的是為被裝飾對象添加新功能。

完整的含義:裝飾器即在不修改裝飾對象源代碼與調(diào)用方式的前提下,為被裝飾器對象添加新功能的一種函數(shù),這個函數(shù)的特殊之處就在于它的返回值也是一個函數(shù)。

一般而言,我們想要拓展原來函數(shù)的代碼,直接的辦法就是侵入代碼里面修改,例如:

import time
def index():
  start_time=time.time()
  time.sleep(3)
  print('hello word')
  stop_time=time.time()
  print('run time is %s'%(stop_time-start_time))
index()

輸出:

hello word
run time is 3.000171422958374

以上代碼就是讓你過三秒才打印'hello word',下面我們要再添加一個新功能,和上面的功能一樣,但是要傳參數(shù)進(jìn)去,過5秒輸出結(jié)果。

修改1:

import time
def index():
  time.sleep(3)
  print('hello word')
def home(name):
  time.sleep(5)
  print('welcome %s to home page'%name)
def wrapper(func):
  start_time=time.time()
  func('haolo')
  stop_time=time.time()
  print('run time is %s'%(stop_time-start_time))
wrapper(home)

輸出:

welcome haolo to home page
run time is 5.000286102294922

這樣寫感覺還是不怎么好,而且我們還修改了函數(shù)的調(diào)用方式,很不符合規(guī)矩。所以我們還是換一種方式來修改它。通過裝飾器的方式。

修改2

import time
def index():
  time.sleep(3)
  print('hello word')
def home(name):
  time.sleep(5)
  print('welcome to %s'%name)
def outter(func): # func為最原始的inde 和home
  def warpper():
    start_time=time.time()
    func('yuan')
    stop_time=time.time()
    print(stop_time-start_time)
  return warpper
home=outter(home) ###home這個變量名是新賦值的,把原來的home給覆蓋了。
home()

輸出:

welcome to yuan
5.000286102294922

這種方式雖然滿足了不修改源代碼和不修改調(diào)用方式的條件,但還是不能夠?qū)崿F(xiàn)兩個函數(shù)同時運(yùn)行的功能,說到底還是不行,我們還得想個方式出來。就是讓他們兩個同時運(yùn)行。這時,我又想到了上節(jié)課所學(xué)的知識,就是*args和**kargs,用兩個函數(shù)通過可變參數(shù)形式來實(shí)現(xiàn)內(nèi)嵌函數(shù)的形式傳入,所以它支持運(yùn)行是構(gòu)建參數(shù)列表,這對于以上兩次不能解決的辦法是最有效的。下面我們來試試,看到底能不能成功。

方式3:

import time
def index():
  time.sleep(3)
  print('hello word')
def home(name):
  time.sleep(5)
  print('welcome %s to home page'%name)
def timmer(func):  #func為最原始的home
  def warpper(*args,**kwargs):
    start_time=time.time()
    res=func(*args,**kwargs) #調(diào)用了最原始的home
    stop_time=time.time()
    print(stop_time-start_time)
    return res
  return warpper
index=timmer(index) #為最新的index = wrapper
home=timmer(home) #為最新的home = wrapper
home(name='yuan') #wrapper=('yuan')
index() #wrapper

輸出:

welcome yuan to home page
5.000285863876343
hello word
3.000171661376953

看吧,很快就實(shí)現(xiàn)了兩個功能并用,而且我們還沒有修改原始代碼,還有調(diào)用方式。

其實(shí)很簡單,我只是用了一個無參裝飾器的模板,這個模板可以說是萬能的,在以后很多的函數(shù)代碼都可以用這種方式來套用。

模板:

def outer(func):
  def inner(*args,**kwargs):
    res=func(*args,**kwargs)
    return res
  return inner

現(xiàn)在又有問題來了,我們調(diào)裝飾器的時候,每調(diào)一次,又要把裝飾器對象傳進(jìn)來,調(diào)一次又傳一次,這樣不會覺得很麻煩嗎?那么我們又想到了一種方法,就是裝飾器語法糖,在被裝飾對象的上面加@timmer 用它來取代 index=timmer(index)

并且把返回值正常的返回給它。

import time
def timmer(func):  #func為最原始的home
  def warpper(*args,**kwargs):
    start_time=time.time()
    res=func(*args,**kwargs) #調(diào)用了最原始的home
    stop_time=time.time()
    print(stop_time-start_time)
    return res
  return warpper
@timmer #就是取代底下的 index=timmer(index)
def index():
  time.sleep(3)
  print('hello word')
@timmer #就是取代底下的home=timmer(home)  home(name='yuan')
def home(name):
  time.sleep(5)
  print('welcome %s to home page'%name)
index()
home('liuyuan')

輸出:

hello word
3.000171661376953
welcome liuyuan to home page
5.000286102294922

注意:這里的timmer函數(shù)就是最原始的裝飾器,它的參數(shù)就是一個函數(shù),然后返回值也是一個函數(shù)。其中作為參數(shù)的這個函數(shù)index()hemo(name)就是在返回函數(shù)的wrapper()的內(nèi)部執(zhí)行。然后再這兩個函數(shù)的前面加上@timmerindex()home(name)函數(shù)就相當(dāng)于被注入了計時功能,現(xiàn)在只需要調(diào)用index()home('yuan'),它就已經(jīng)變身為'新功能更多的函數(shù)了。'

所以這里的裝飾器就像一個注入的符號:有了它,拓展了原來函數(shù)的功能既不需要侵入函數(shù)內(nèi)更改代碼,也不需要重復(fù)執(zhí)行原函數(shù)。

用裝飾器來實(shí)現(xiàn)認(rèn)證功能:

import time
current_user={
  'username':None,
  #'login_time':None
}
def auth(func):
  # func = index
  def wrapper(*args,**kwargs):
    if current_user['username']:
      print('已經(jīng)登錄過了')
      res=func(*args,**kwargs)
      return res
    uname = input('輸入用戶名:').strip()
    pwd = input('密碼:').strip()
    if uname == 'yuan' and pwd == '123':
      print('登錄成功')
      current_user['username']=uname
      res = func(*args,**kwargs)
      return res
    else:
      print('用戶名或密碼錯誤')
  return wrapper
@auth #index = auth(index)
def index():
  time.sleep(1)
  print('welcom to index page')
@auth
def home(name):
  time.sleep(2)
  print('welcome %s to home page'%name)
input()
home('yuan')

有參數(shù)的裝飾器來用于用戶認(rèn)證

import time
current_user={
  'username':None,
  # 'login_time':None
}
def auth(func):
  # func=index
  def wrapper(*args,**kwargs):
    if current_user['username']:
      print('已經(jīng)登陸過了')
      res=func(*args,**kwargs)
      return res
    uname=input('用戶名>>: ').strip()
    pwd=input('密碼>>: ').strip()
    if uname == 'yuan' and pwd == '123':
      print('登陸成功')
      current_user['username']=uname
      res=func(*args,**kwargs)
      return res
    else:
      print('用戶名或密碼錯誤')
  return wrapper
def timmer(func):
  def wrapper(*args,**kwargs):
    start_time=time.time()
    res=func(*args,**kwargs)
    stop_time=time.time()
    print(stop_time-start_time)
    return res
  return wrapper
@timmer # timmer 統(tǒng)計的是auth+index的執(zhí)行時間
@auth
def index():
  time.sleep(1)
  print('welcome to index page')
  return 122
index()

疊加多個裝飾器:

import time
current_user={
  'username':None,
  # 'login_time':None
}
def auth(func):
  # func=index
  def wrapper(*args,**kwargs):
    if current_user['username']:
      print('已經(jīng)登陸過了')
      res=func(*args,**kwargs)
      return res
    uname=input('用戶名>>: ').strip()
    pwd=input('密碼>>: ').strip()
    if uname == 'egon' and pwd == '123':
      print('登陸成功')
      current_user['username']=uname
      res=func(*args,**kwargs)
      return res
    else:
      print('用戶名或密碼錯誤')
  return wrapper
def timmer(func):
  def wrapper(*args,**kwargs):
    start_time=time.time()
    res=func(*args,**kwargs)
    stop_time=time.time()
    print(stop_time-start_time)
    return res
  return wrapper
@timmer # timmer 統(tǒng)計的是auth+index的執(zhí)行時間
@auth
def index():
  time.sleep(1)
  print('welcome to index page')
  return 122
index()

python的五大特點(diǎn)是什么

python的五大特點(diǎn):1.簡單易學(xué),開發(fā)程序時,專注的是解決問題,而不是搞明白語言本身。2.面向?qū)ο?,與其他主要的語言如C++和Java相比, Python以一種非常強(qiáng)大又簡單的方式實(shí)現(xiàn)面向?qū)ο缶幊獭?.可移植性,Python程序無需修改就可以在各種平臺上運(yùn)行。4.解釋性,Python語言寫的程序不需要編譯成二進(jìn)制代碼,可以直接從源代碼運(yùn)行程序。5.開源,Python是 FLOSS(自由/開放源碼軟件)之一。

以上就是如何在Python中使用函數(shù)裝飾器,小編相信有部分知識點(diǎn)可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI