在线不卡日本ⅴ一区v二区_精品一区二区中文字幕_天堂v在线视频_亚洲五月天婷婷中文网站

  • <menu id="lky3g"></menu>
  • <style id="lky3g"></style>
    <pre id="lky3g"><tt id="lky3g"></tt></pre>

    python中的裝飾器

    裝飾器(Decorators)是Python的一個重要部分。簡單地說:他們是修改其他函數(shù)功能的函數(shù)。他們有助于讓我們的代碼簡短,也更符合Python規(guī)范(Pythonic)。

    def a_new_decorator(a_func): def wrapTheFunction(): print(“I am doing some boring work before executing a_func()”) a_func() print(“I am doing some boring work after executing a_func()”) return wrapTheFunctiondef a_function_requiring_decoration(): print(“I am the function which needs some decoration to remove my foul smell”)a_function_requiring_decoration()#outputs: “I am the function which needs some decoration to remove my foul smell”a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)#now a_function_requiring_decoration is wrapped by wrapTheFunction()a_function_requiring_decoration()#outputs:I am doing some boring work before executing a_func()# I am the function which needs some decoration to remove my foul smell# I am doing some boring work after executing a_func()

    上面的代碼可以更簡潔一些:

    def a_new_decorator(a_func): def wrapTheFunction(): print(“I am doing some boring work before executing a_func()”) a_func() print(“I am doing some boring work after executing a_func()”) return wrapTheFunction@a_new_decoratordef a_function_requiring_decoration(): print(“I am the function which needs some decoration to remove my foul smell”)a_function_requiring_decoration()#outputs:I am doing some boring work before executing a_func()# I am the function which needs some decoration to remove my foul smell# I am doing some boring work after executing a_func()

    其中@a_new_decorator(注意語句位置,須位于被裝修函數(shù)之前)等價于下列語句:

    a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)

    如果需要獲取被裝飾函數(shù)的函數(shù)名,需要使用functools.wraps函數(shù):

    from functools import wrapsdef a_new_decorator(a_func): @wraps(a_func) def wrapTheFunction(): print(“I am doing some boring work before executing a_func()”) a_func() print(“I am doing some boring work after executing a_func()”) return wrapTheFunction@a_new_decoratordef a_function_requiring_decoration(): “””Hey yo! Decorate me!””” print(“I am the function which needs some decoration to ” “remove my foul smell”)print(a_function_requiring_decoration.__name__)# Output: a_function_requiring_decoration

    否則,print(a_function_requiring_decoration.__name__)的返回結果將是wrapTheFunction。

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

    from functools import wrapsdef 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

    日志是裝飾器運用的另一個亮點。這是個例子:

    from functools import wrapsdef logit(func): @wraps(func) def with_logging(*args, **kwargs): print(func.__name__ + ” was called”) return func(*args, **kwargs) return with_logging@logitdef addition_func(x): “””Do some math.””” return x + xresult = addition_func(4)# Output: addition_func was called

    裝飾器也可以帶參數(shù),我們將上面日志的例子修改一下,允許指定保存日志的位置:

    from functools import wrapsdef logit(logfile=’out.log’): def logging_decorator(func): @wraps(func) def wrapped_function(*args, **kwargs): log_string = func.__name__ + ” was called” print(log_string) # Open the logfile and append with open(logfile, ‘a’) as opened_file: # Now we log to the specified logfile opened_file.write(log_string + ”) return func(*args, **kwargs) return wrapped_function return logging_decorator@logit()def myfunc1(): passmyfunc1()# Output: myfunc1 was called# A file called out.log now exists, with the above string@logit(logfile=’func2.log’)def myfunc2(): passmyfunc2()# Output: myfunc2 was called# A file called func2.log now exists, with the above string

    類也可以用來構建裝飾器:

    class logit(object): _logfile = ‘out.log’ def __init__(self, func): self.func = func def __call__(self, *args): log_string = self.func.__name__ + ” was called” print(log_string) # Open the logfile and append with open(self._logfile, ‘a’) as opened_file: # Now we log to the specified logfile opened_file.write(log_string + ”) # Now, send a notification self.notify() # return base func return self.func(*args) def notify(self): # logit only logs, no more pass

    這個實現(xiàn)有一個附加優(yōu)勢,在于比嵌套函數(shù)的方式更加整潔,而且包裹一個函數(shù)還是使用跟以前一樣的語法:

    logit._logfile = ‘out2.log’ # if change log file@logitdef myfunc1(): passmyfunc1()# Output: myfunc1 was called

    我們給logit創(chuàng)建子類,來添加email的功能。

    class email_logit(logit): ”’ A logit implementation for sending emails to admins when the function is called. ”’ def __init__(self, email=’[email protected]’, *args, **kwargs): self.email = email super(email_logit, self).__init__(*args, **kwargs) def notify(self): # Send an email to self.email # Will not be implemented here pass

    鄭重聲明:本文內容及圖片均整理自互聯(lián)網(wǎng),不代表本站立場,版權歸原作者所有,如有侵權請聯(lián)系管理員(admin#wlmqw.com)刪除。
    用戶投稿
    上一篇 2022年6月19日 15:13
    下一篇 2022年6月19日 15:13

    相關推薦

    • 存儲過程語法(sql server存儲過程語法)

      今天小編給各位分享存儲過程語法的知識,其中也會對sql server存儲過程語法進行解釋,如果能碰巧解決你現(xiàn)在面臨的問題,別忘了關注本站,現(xiàn)在開始吧! oracle存儲過程基本語法…

      2022年11月26日
    • 全民K歌升級新版本7.0之后,有哪些隱藏功能?

      作者:高百烈來源:知乎 這個功能,舊版并沒有,要升級到全新的全民K歌7.0版本才能發(fā)現(xiàn)。 作為朋友圈當代K歌之王,我費了不少功夫才搶到內測版本。有一說一,全民K歌的路子真的很野,新…

      2022年11月25日
    • 《光遇》11月25日紅石在哪里 11.25紅石位置

      光遇11月25日的紅石出現(xiàn)在霞谷圓夢村,許多小伙伴都還不知道它具體在哪,下面就讓小編來給大家介紹一下光遇11.25紅石的位置,感興趣的小伙伴快來看看吧。 光遇11.25紅石位置 1…

      2022年11月25日
    • 《光遇》11月25日季節(jié)蠟燭在哪 11.25季節(jié)蠟燭位置2022

      光遇季節(jié)蠟燭的位置每天都會變化,今天出現(xiàn)在了雨林地區(qū),下面小編就給大家?guī)砹斯庥?1.25季節(jié)蠟燭位置分享,有需要的小伙伴不要錯過哦。 光遇11.25季節(jié)蠟燭位置2022 今日季節(jié)…

      2022年11月25日
    • 上手Reno8 Pro體驗跨屏互聯(lián) 實在太方便!

      11月已經來到了月底,在手機品牌又要推出新一年度的新品手機之前,我們來點評一下今年令人驚喜的產品。如OPPO的Reno8 Pro系列,該系列搭載雙芯影像配置獲得了很多消費者的認可?!?/p>

      2022年11月25日
    • 什么是推廣cpa一篇文章帶你看懂CPA推廣渠道

      CPA渠道 CPA指的是按照指定的行為結算,可以是搜索,可以是注冊,可以是激活,可以是搜索下載激活,可以是綁卡,實名認證,可以是付費,可以是瀏覽等等。甲乙雙方可以根據(jù)自己的情況來定…

      2022年11月25日
    • 《寶可夢朱紫》樁子是什么?二級神封印樁位置一覽

      寶可夢朱紫中有一種叫做二級神封印樁的特殊收集道具,很多玩家不知道寶可夢朱紫樁子是什么,下面就帶來寶可夢朱紫二級神封印樁位置一覽,感興趣的小伙伴不要錯過,希望能幫助到大家。 二級神封…

      2022年11月24日
    • 《寶可夢朱紫》太晶水地龍捕捉位置一覽 太晶水地龍在哪里捕捉

      近日在貼吧看到有許多玩家在寶可夢朱紫中遇到了《寶可夢朱紫》太晶水地龍捕捉位置一覽的問題,又不知道該怎么辦。今天在這里,小編為大家?guī)淼木褪沁@個問題的解方案,只要你跟著小編的節(jié)奏來,…

      2022年11月24日
    • 華為手機怎么掃一掃連接wifi(手機掃一掃在哪里)

      手機瀏覽器可以用來瀏覽網(wǎng)頁、看新聞、看視頻,還能搜索問題,在我們的工作生活中瀏覽器占據(jù)著非常重要的位置。手機瀏覽器除了這些作用,其實它隱藏著其他功能,比如:掃一掃。掃一掃可不只是用…

      2022年11月24日
    • 三星手機截屏(三星手機截屏圖片在哪個文件夾)

      本文主要講的是三星手機截屏,以及和三星手機截屏圖片在哪個文件夾相關的知識,如果覺得本文對您有所幫助,不要忘了將本文分享給朋友。 三星手機截屏怎么截 三星手機四種截屏方法 1、普通截…

      2022年11月24日

    聯(lián)系我們

    聯(lián)系郵箱:admin#wlmqw.com
    工作時間:周一至周五,10:30-18:30,節(jié)假日休息