欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python 裝飾器原理、定義與用法詳解

 更新時(shí)間:2019年12月07日 10:18:31   作者:code_designer  
這篇文章主要介紹了Python 裝飾器原理、定義與用法,結(jié)合實(shí)例形式分析了Python裝飾器的概念、定義、實(shí)現(xiàn)方法、應(yīng)用場(chǎng)景及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下

本文實(shí)例講述了Python 裝飾器原理、定義與用法。分享給大家供大家參考,具體如下:

Python 裝飾器

一、何為裝飾器

1、在函數(shù)中定義函數(shù)

在函數(shù)中定義另外的函數(shù),就是說可以創(chuàng)建嵌套的函數(shù),例子如下

def sayHi(name="hjj2"):
 print 'inside sayHi() func'
 def greet():
  return 'inside greet() func'
 print(greet())
sayHi()
#output
#  inside sayHi() func
#  inside greet() func

2、將函數(shù)作為參數(shù)傳給另外一個(gè)函數(shù),裝飾器原型

def sayHi():
 return 'hi hjj2'
def doSthBeforeSayHi(func):
 print 'before sayHi func'
 print(func())
doSthBeforeSayHi(sayHi)
#output
#  before sayHi func
#  hi hjj2

3、實(shí)現(xiàn)一個(gè)裝飾器

在第二步中,我們已經(jīng)基本探究到裝飾器的原理了,python裝飾器做的事就是通過封裝一個(gè)函數(shù)并且用這樣或那樣的方式來修改它的行為。不帶@的初步示例如下:

def new_decorator(func):
  def wrapDecorator():
   print 'before func'
   func()
   print 'after func'
  return wrapDecorator
def func_require_decorator():
  print 'a func need decorator'
func_require_decorator()
#ouput: a func need decorator
func_require_decorator = new_decorator(func_require_decorator)
func_require_decorator()
#ouput:
#  before func
#  a func need decorator
#  after func

使用@來運(yùn)行裝飾器

@new_decorator
func_require_decorator()
#ouput:
#  before func
#  a func need decorator
#  after func

這里我們可以看到,這兩個(gè)例子的運(yùn)行結(jié)果是一樣的。所以我們能想象得到@new_decorator的作用就是

func_require_decorator = new_decorator(func_require_decorator)

我們繼續(xù)優(yōu)化這個(gè)裝飾器,現(xiàn)在我們有一個(gè)問題就是,如果我們想要通過print(func_require_decorator.__name__)就會(huì)報(bào)錯(cuò)# Output: wrapTheFunction。這樣就需要借助python提供的functools.wraps來解決了

@wraps接受一個(gè)函數(shù)來進(jìn)行裝飾,并加入了復(fù)制函數(shù)名稱、注釋文檔、參數(shù)列表等等的功能。這可以讓我們?cè)谘b飾器里面訪問在裝飾之前的函數(shù)的屬性。

from functools import wraps
def new_decorator(func):
  @wraps(func)
  def wrapDecorator():
   print 'before func'
   func()
   print 'after func'
  return wrapDecorator
def func_require_decorator():
  print 'a func need decorator'
@new_decorator
func_require_decorator()
print(func_require_decorator.__name__)
#ouput: func_require_decorator

二、使用場(chǎng)景

1、授權(quán),大體例子

from functools import wraps
def requires_auth(f):
  @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

2、日志:

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)
      with open(logfile,'a') as opened_file:
        opened_file.write(log_string+'\n')
      return func(*args,**kwargs)
    return wrapped_function
  return logging_decorator
@logit()
def func1():
  pass
func1()

3、其他如flask中的@app.route()

三、裝飾器類

1、將上面的日志裝飾器變?yōu)轭惖某醪侥P腿缦?/strong>

from functools import wraps
class logit(object):
  def __init__(self, logfile='out.log'):
    self.logfile = logfile
  def __call__(self, func):
    @wraps(func)
    def wrapped_function(*args, **kwargs):
      log_string = func.__name__ + "was called"
      print(log_string)
      # 打開logfile并寫入
      with open(self.logfile, 'a') as open_file:
        # 將日志寫到指定文件
        open_file.write(log_string + '\n')
      # 發(fā)送一個(gè)通知
      self.notify()
      return func(*args, **kwargs)
    return wrapped_function
  def notify(self):
    pass
@logit()
def myfunc1():
  pass
class email_logit(logit):
  '''
  實(shí)現(xiàn)在函數(shù)調(diào)用時(shí)發(fā)送email
  '''
  def __init__(self, email='admin@xxx.com', *args, **kwargs):
    self.email = email
    super(email_logit, self).__init__(*args, **kwargs)
  def notify(self):
    '''
    發(fā)送郵件通知
    '''
    pass

通過這種方式,我們可以定義我們?cè)谧约旱男枨?,減少代碼的冗余,提高復(fù)用率。

至此,關(guān)于裝飾器的探索就結(jié)束啦。

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python面向?qū)ο蟪绦蛟O(shè)計(jì)入門與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進(jìn)階經(jīng)典教程

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • python的xpath獲取div標(biāo)簽內(nèi)html內(nèi)容,實(shí)現(xiàn)innerhtml功能的方法

    python的xpath獲取div標(biāo)簽內(nèi)html內(nèi)容,實(shí)現(xiàn)innerhtml功能的方法

    今天小編就為大家分享一篇python的xpath獲取div標(biāo)簽內(nèi)html內(nèi)容,實(shí)現(xiàn)innerhtml功能的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • python筆記_將循環(huán)內(nèi)容在一行輸出的方法

    python筆記_將循環(huán)內(nèi)容在一行輸出的方法

    今天小編就為大家分享一篇python筆記_將循環(huán)內(nèi)容在一行輸出的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • Flask-WTF表單的使用方法

    Flask-WTF表單的使用方法

    這篇文章主要介紹了Flask-WTF表單的使用方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • pyCharm 設(shè)置調(diào)試輸出窗口中文顯示方式(字符碼轉(zhuǎn)換)

    pyCharm 設(shè)置調(diào)試輸出窗口中文顯示方式(字符碼轉(zhuǎn)換)

    這篇文章主要介紹了pyCharm 設(shè)置調(diào)試輸出窗口中文顯示方式(字符碼轉(zhuǎn)換),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • Pytorch之tensorboard無法啟動(dòng)和顯示問題及解決

    Pytorch之tensorboard無法啟動(dòng)和顯示問題及解決

    這篇文章主要介紹了Pytorch之tensorboard無法啟動(dòng)和顯示問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • 使用Python編程分析火爆全網(wǎng)的魷魚游戲豆瓣影評(píng)

    使用Python編程分析火爆全網(wǎng)的魷魚游戲豆瓣影評(píng)

    本文來為大家介紹如何使用Python爬取影評(píng)的操作,主要是爬取《魷魚游戲》在豆瓣上的一些影評(píng),對(duì)數(shù)據(jù)做一些簡(jiǎn)單的分析,用數(shù)據(jù)的角度重新審視下這部劇,有需要的朋友可以借鑒參考下
    2021-10-10
  • Python數(shù)據(jù)分析:手把手教你用Pandas生成可視化圖表的教程

    Python數(shù)據(jù)分析:手把手教你用Pandas生成可視化圖表的教程

    今天小編就為大家分享一篇Python數(shù)據(jù)分析:手把手教你用Pandas生成可視化圖表的教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • 詳解如何用Python登錄豆瓣并爬取影評(píng)

    詳解如何用Python登錄豆瓣并爬取影評(píng)

    這篇文章主要介紹了如何用Python登錄豆瓣并爬取影評(píng),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-08-08
  • python3 如何解壓縮.gz文件

    python3 如何解壓縮.gz文件

    這篇文章主要介紹了python3 如何解壓縮.gz文件,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-09-09
  • 淺談numpy數(shù)組初始化的幾種方法

    淺談numpy數(shù)組初始化的幾種方法

    本文主要介紹了淺談numpy數(shù)組初始化的幾種方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07

最新評(píng)論