亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python裝飾器實(shí)現(xiàn)方法及應(yīng)用場(chǎng)景詳解

 更新時(shí)間:2020年03月26日 11:38:00   作者:Python熱愛者  
這篇文章主要介紹了Python裝飾器實(shí)現(xiàn)方法及應(yīng)用場(chǎng)景詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

應(yīng)用場(chǎng)景:

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ù)。

幸運(yùn)的是,類也可以用來構(gòu)建裝飾器。那我們現(xiàn)在以一個(gè)類而不是一個(gè)函數(shù)的方式,來重新構(gòu)建logit。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論