亚洲精品中文免费|亚洲日韩中文字幕制服|久久精品亚洲免费|一本之道久久免费

      
      

            <dl id="hur0q"><div id="hur0q"></div></dl>

                python中的裝飾器

                裝飾器(Decorators)是Python的一個(gè)重要部分。簡(jiǎn)單地說:他們是修改其他函數(shù)功能的函數(shù)。他們有助于讓我們的代碼簡(jiǎn)短,也更符合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()

                上面的代碼可以更簡(jiǎn)潔一些:

                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ù)之前)等價(jià)于下列語句:

                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__)的返回結(jié)果將是wrapTheFunction。

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

                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

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

                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

                類也可以用來構(gòu)建裝飾器:

                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

                這個(gè)實(shí)現(xiàn)有一個(gè)附加優(yōu)勢(shì),在于比嵌套函數(shù)的方式更加整潔,而且包裹一個(gè)函數(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

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

                相關(guān)推薦

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                  2022年11月24日
                • 《寶可夢(mèng)朱紫》太晶水地龍捕捉位置一覽 太晶水地龍?jiān)谀睦锊蹲?

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

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

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

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

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

                  2022年11月24日

                聯(lián)系我們

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