溫馨提示×

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

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

怎么在Python中實(shí)現(xiàn)一個(gè)裝飾器

發(fā)布時(shí)間:2021-04-16 16:37:22 來源:億速云 閱讀:139 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章給大家介紹怎么在Python中實(shí)現(xiàn)一個(gè)裝飾器,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

1、授權(quán)(Authorization)

裝飾器能有助于檢查某個(gè)人是否被授權(quán)去使用一個(gè)web應(yīng)用的端點(diǎn)(endpoint)。它們被大量使用于Flask和Django web框架中。這里是一個(gè)例子來使用基于裝飾器的授權(quán):

from functools import wraps  # 最新版python引用是 import functools

def requires_auth(f):  # f 就是我們需要裝飾的函數(shù),一看就是不帶參數(shù)的裝飾器
  @wraps(f)   # 新版python寫法 @functools.wraps(f)
  def decorated(*args, **kwargs):
    auth = request.authorization
    if not auth or not check_auth(auth.username, auth.password):
      authenticate()
    return f(*args, **kwargs)
  return decorated  # 該裝飾器需相關(guān)配置才能運(yùn)行,這里是截取代碼展示應(yīng)用

2.、日志(Logging)

日志是裝飾器運(yùn)用的另一個(gè)亮點(diǎn)。這是個(gè)例子:

from functools import wraps
def logit(func):
  @wraps(func)
  def with_logging(*args, **kwargs):
    print(func.__name__ + " was called")
    return func(*args, **kwargs)
  return with_logging

@logit
def addition_func(x):
  """Do some math."""
  return x + x
result = addition_func(4)

我敢肯定你已經(jīng)在思考裝飾器的一個(gè)其他聰明用法了。

3.、帶參數(shù)的裝飾器

帶參數(shù)的裝飾器是典型的閉包函數(shù)

4.、在函數(shù)中嵌入裝飾器

我們回到日志的例子,并創(chuàng)建一個(gè)包裹函數(shù),能讓我們指定一個(gè)用于輸出的日志文件

from functools import wraps

def logit(logfile='out.log'):
  def logging_decorator(func):
    @wraps(func)
    def wrapped_function(*args, **kwargs):
      log_string = func.__name__ + " was called"
      print(log_string)
      # 打開logfile,并寫入內(nèi)容
      with open(logfile, 'a') as opened_file:
        # 現(xiàn)在將日志打到指定的logfile
        opened_file.write(log_string + '\n')
      return func(*args, **kwargs)
    return wrapped_function
  return logging_decorator
@logit()
def myfunc1():
  pass
myfunc1()
# Output: myfunc1 was called
# 現(xiàn)在一個(gè)叫做 out.log 的文件出現(xiàn)了,里面的內(nèi)容就是上面的字符串
@logit(logfile='func2.log')
def myfunc2():
  pass
myfunc2()
# Output: myfunc2 was called
# 現(xiàn)在一個(gè)叫做 func2.log 的文件出現(xiàn)了,里面的內(nèi)容就是上面的字符串

5.、裝飾器類

現(xiàn)在我們有了能用于正式環(huán)境的logit裝飾器,但當(dāng)我們的應(yīng)用的某些部分還比較脆弱時(shí),異常也許是需要更緊急關(guān)注的事情。比方說有時(shí)你只想打日志到一個(gè)文件。而有時(shí)你想把引起你注意的問題發(fā)送到一個(gè)email,同時(shí)也保留日志,留個(gè)記錄。這是一個(gè)使用繼承的場(chǎng)景,但目前為止我們只看到過用來構(gòu)建裝飾器的函數(shù)。

關(guān)于怎么在Python中實(shí)現(xiàn)一個(gè)裝飾器就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

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

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

AI