裝飾器在python里面有很重要的作用, 如果能夠熟練使用,將會(huì)大大的提高工作效率
今天就來(lái)見(jiàn)識(shí)一下 python 裝飾器,到底是怎么工作的。
本文主要是利用python裝飾器計(jì)算函數(shù)運(yùn)行時(shí)間
一些需要精確的計(jì)算函數(shù)運(yùn)行了多久的程序,都可以采用這種方法
#coding:utf-8 import urllib2,re,time,random,os,datetime import HTMLParser import sys reload(sys) sys.setdefaultencoding('utf-8') #計(jì)算時(shí)間函數(shù) def print_run_time(func): def wrapper(*args, **kw): local_time = time.time() func(*args, **kw) print 'current Function [%s] run time is %.2f' % (func.__name__ ,time.time() - local_time) return wrapper class test: def __init__(self): self.url='' #獲取網(wǎng)頁(yè)頁(yè)面內(nèi)容 #即裝飾器不管參數(shù)有多少,都能使用 @print_run_time def get_html(self,url): headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.2; rv:16.0) Gecko/20100101 Firefox/16.0'}#設(shè)置header req = urllib2.Request(url=url,headers=headers) try: html = urllib2.urlopen(req).read().decode('utf-8') html=HTMLParser.HTMLParser().unescape(html)#處理網(wǎng)頁(yè)內(nèi)容, 可以將一些html類型的符號(hào)如" 轉(zhuǎn)換回雙引號(hào) #html = html.decode('utf-8','replace').encode(sys.getfilesystemencoding())#轉(zhuǎn)碼:避免輸出出現(xiàn)亂碼 except urllib2.HTTPError,e: print(2,u"連接頁(yè)面失敗,錯(cuò)誤原因: %s" % e.code) return None except urllib2.URLError,e: if hasattr(e,'reason'): print(2,u"連接頁(yè)面失敗,錯(cuò)誤原因:%s" % e.reason) return None return html #在類的內(nèi)部使用裝飾器 @print_run_time def run(self): self.url='http://www.baidu.com' self.get_html(self.url) print 'end' #在外面直接使用裝飾器 @print_run_time def get_current_dir(spath): #spath=os.getcwd() #spath=os.path.abspath(os.curdir) for schild in os.listdir(spath): schildpath=spath+'/'+schild if os.path.isdir(schildpath): get_current_dir(schildpath) else: print schildpath if __name__ == '__main__': my_test=test() my_test.run() spath=os.path.abspath('.') get_current_dir(spath)
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。