本文實(shí)例講述了Python中的裝飾器用法。分享給大家供大家參考。具體分析如下:
這里還是先由stackoverflow上面的一個(gè)問(wèn)題引起吧,如果使用如下的代碼:
@makebold
@makeitalic
def say():
return "Hello"
打印出如下的輸出:<b><i>Hello<i></b>
你會(huì)怎么做?最后給出的答案是:
def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makebold
@makeitalic
def hello():
return "hello world"
print hello() ## 返回 <b><i>hello world</i></b>
現(xiàn)在我們來(lái)看看如何從一些最基礎(chǔ)的方式來(lái)理解Python的裝飾器。裝飾器是一個(gè)很著名的設(shè)計(jì)模式,經(jīng)常被用于有切面需求的場(chǎng)景,較為經(jīng)典的有插入日志、性能測(cè)試、事務(wù)處理等。裝飾器是解決這類(lèi)問(wèn)題的絕佳設(shè)計(jì),有了裝飾器,我們就可以抽離出大量函數(shù)中與函數(shù)功能本身無(wú)關(guān)的雷同代碼并繼續(xù)重用。概括的講,裝飾器的作用就是為已經(jīng)存在的對(duì)象添加額外的功能。
1.1. 需求是怎么來(lái)的?
裝飾器的定義很是抽象,我們來(lái)看一個(gè)小例子。
def foo():
print 'in foo()'
foo()
這是一個(gè)很無(wú)聊的函數(shù)沒(méi)錯(cuò)。但是突然有一個(gè)更無(wú)聊的人,我們稱(chēng)呼他為B君,說(shuō)我想看看執(zhí)行這個(gè)函數(shù)用了多長(zhǎng)時(shí)間,好吧,那么我們可以這樣做:
import time
def foo():
start = time.clock()
print 'in foo()'
end = time.clock()
print 'used:', end - start
foo()
很好,功能看起來(lái)無(wú)懈可擊??墒堑疤鄣腂君此刻突然不想看這個(gè)函數(shù)了,他對(duì)另一個(gè)叫foo2的函數(shù)產(chǎn)生了更濃厚的興趣。怎么辦呢?如果把以上新增加的代碼復(fù)制到foo2里,這就犯了大忌了~復(fù)制什么的難道不是最討厭了么!而且,如果B君繼續(xù)看了其他的函數(shù)呢?
1.2. 以不變應(yīng)萬(wàn)變,是變也
還記得嗎,函數(shù)在Python中是一等公民,那么我們可以考慮重新定義一個(gè)函數(shù)timeit,將foo的引用傳遞給他,然后在timeit中調(diào)用foo并進(jìn)行計(jì)時(shí),這樣,我們就達(dá)到了不改動(dòng)foo定義的目的,而且,不論B君看了多少個(gè)函數(shù),我們都不用去修改函數(shù)定義了!
import time
def foo():
print 'in foo()'
def timeit(func):
start = time.clock()
func()
end =time.clock()
print 'used:', end - start
timeit(foo)
看起來(lái)邏輯上并沒(méi)有問(wèn)題,一切都很美好并且運(yùn)作正常!……等等,我們似乎修改了調(diào)用部分的代碼。原本我們是這樣調(diào)用的:foo(),修改以后變成了:timeit(foo)。這樣的話,如果foo在N處都被調(diào)用了,你就不得不去修改這N處的代碼?;蛘吒鼧O端的,考慮其中某處調(diào)用的代碼無(wú)法修改這個(gè)情況,比如:這個(gè)函數(shù)是你交給別人使用的。1.3. 最大限度地少改動(dòng)!
既然如此,我們就來(lái)想想辦法不修改調(diào)用的代碼;如果不修改調(diào)用代碼,也就意味著調(diào)用foo()需要產(chǎn)生調(diào)用timeit(foo)的效果。我們可以想到將timeit賦值給foo,但是timeit似乎帶有一個(gè)參數(shù)……想辦法把參數(shù)統(tǒng)一吧!如果timeit(foo)不是直接產(chǎn)生調(diào)用效果,而是返回一個(gè)與foo參數(shù)列表一致的函數(shù)的話……就很好辦了,將timeit(foo)的返回值賦值給foo,然后,調(diào)用foo()的代碼完全不用修改!
#-*- coding: UTF-8 -*-
import time
def foo():
print 'in foo()'
# 定義一個(gè)計(jì)時(shí)器,傳入一個(gè),并返回另一個(gè)附加了計(jì)時(shí)功能的方法
def timeit(func):
# 定義一個(gè)內(nèi)嵌的包裝函數(shù),給傳入的函數(shù)加上計(jì)時(shí)功能的包裝
def wrapper():
start = time.clock()
func()
end =time.clock()
print 'used:', end - start
# 將包裝后的函數(shù)返回
return wrapper
foo = timeit(foo)
foo()
這樣,一個(gè)簡(jiǎn)易的計(jì)時(shí)器就做好了!我們只需要在定義foo以后調(diào)用foo之前,加上foo = timeit(foo),就可以達(dá)到計(jì)時(shí)的目的,這也就是裝飾器的概念,看起來(lái)像是foo被timeit裝飾了。在在這個(gè)例子中,函數(shù)進(jìn)入和退出時(shí)需要計(jì)時(shí),這被稱(chēng)為一個(gè)橫切面(Aspect),這種編程方式被稱(chēng)為面向切面的編程(Aspect-Oriented Programming)。與傳統(tǒng)編程習(xí)慣的從上往下執(zhí)行方式相比較而言,像是在函數(shù)執(zhí)行的流程中橫向地插入了一段邏輯。在特定的業(yè)務(wù)領(lǐng)域里,能減少大量重復(fù)代碼。面向切面編程還有相當(dāng)多的術(shù)語(yǔ),這里就不多做介紹,感興趣的話可以去找找相關(guān)的資料。這個(gè)例子僅用于演示,并沒(méi)有考慮foo帶有參數(shù)和有返回值的情況,完善它的重任就交給你了 :)
上面這段代碼看起來(lái)似乎已經(jīng)不能再精簡(jiǎn)了,Python于是提供了一個(gè)語(yǔ)法糖來(lái)降低字符輸入量。
import time
def timeit(func):
def wrapper():
start = time.clock()
func()
end =time.clock()
print 'used:', end - start
return wrapper
@timeit
def foo():
print 'in foo()'
foo()
重點(diǎn)關(guān)注第11行的@timeit,在定義上加上這一行與另外寫(xiě)foo = timeit(foo)完全等價(jià),千萬(wàn)不要以為@有另外的魔力。除了字符輸入少了一些,還有一個(gè)額外的好處:這樣看上去更有裝飾器的感覺(jué)。要理解python的裝飾器,我們首先必須明白在Python中函數(shù)也是被視為對(duì)象。這一點(diǎn)很重要。先看一個(gè)例子:
def shout(word="yes") :
return word.capitalize()+" !"
print shout()
# 輸出 : 'Yes !'
# 作為一個(gè)對(duì)象,你可以把函數(shù)賦給任何其他對(duì)象變量
scream = shout
# 注意我們沒(méi)有使用圓括號(hào),因?yàn)槲覀儾皇窃谡{(diào)用函數(shù)
# 我們把函數(shù)shout賦給scream,也就是說(shuō)你可以通過(guò)scream調(diào)用shout
print scream()
# 輸出 : 'Yes !'
# 還有,你可以刪除舊的名字shout,但是你仍然可以通過(guò)scream來(lái)訪問(wèn)該函數(shù)
del shout
try :
print shout()
except NameError, e :
print e
#輸出 : "name 'shout' is not defined"
print scream()
# 輸出 : 'Yes !'
我們暫且把這個(gè)話題放旁邊,我們先看看python另外一個(gè)很有意思的屬性:可以在函數(shù)中定義函數(shù):
def talk() :
# 你可以在talk中定義另外一個(gè)函數(shù)
def whisper(word="yes") :
return word.lower()+"...";
# ... 并且立馬使用它
print whisper()
# 你每次調(diào)用'talk',定義在talk里面的whisper同樣也會(huì)被調(diào)用
talk()
# 輸出 :
# yes...
# 但是"whisper" 不會(huì)單獨(dú)存在:
try :
print whisper()
except NameError, e :
print e
#輸出 : "name 'whisper' is not defined"*
函數(shù)引用從以上兩個(gè)例子我們可以得出,函數(shù)既然作為一個(gè)對(duì)象,因此:
1. 其可以被賦給其他變量
2. 其可以被定義在另外一個(gè)函數(shù)內(nèi)
這也就是說(shuō),函數(shù)可以返回一個(gè)函數(shù),看下面的例子:
def getTalk(type="shout") :
# 我們定義另外一個(gè)函數(shù)
def shout(word="yes") :
return word.capitalize()+" !"
def whisper(word="yes") :
return word.lower()+"...";
# 然后我們返回其中一個(gè)
if type == "shout" :
# 我們沒(méi)有使用(),因?yàn)槲覀儾皇窃谡{(diào)用該函數(shù)
# 我們是在返回該函數(shù)
return shout
else :
return whisper
# 然后怎么使用呢 ?
# 把該函數(shù)賦予某個(gè)變量
talk = getTalk()
# 這里你可以看到talk其實(shí)是一個(gè)函數(shù)對(duì)象:
print talk
#輸出 : <function shout at 0xb7ea817c>
# 該對(duì)象由函數(shù)返回的其中一個(gè)對(duì)象:
print talk()
# 或者你可以直接如下調(diào)用 :
print getTalk("whisper")()
#輸出 : yes...
還有,既然可以返回一個(gè)函數(shù),我們可以把它作為參數(shù)傳遞給函數(shù):
def doSomethingBefore(func) :
print "I do something before then I call the function you gave me"
print func()
doSomethingBefore(scream)
#輸出 :
#I do something before then I call the function you gave me
#Yes !
這里你已經(jīng)足夠能理解裝飾器了,其他它可被視為封裝器。也就是說(shuō),它能夠讓你在裝飾前后執(zhí)行代碼而無(wú)須改變函數(shù)本身內(nèi)容。手工裝飾
那么如何進(jìn)行手動(dòng)裝飾呢?
# 裝飾器是一個(gè)函數(shù),而其參數(shù)為另外一個(gè)函數(shù)
def my_shiny_new_decorator(a_function_to_decorate) :
# 在內(nèi)部定義了另外一個(gè)函數(shù):一個(gè)封裝器。
# 這個(gè)函數(shù)將原始函數(shù)進(jìn)行封裝,所以你可以在它之前或者之后執(zhí)行一些代碼
def the_wrapper_around_the_original_function() :
# 放一些你希望在真正函數(shù)執(zhí)行前的一些代碼
print "Before the function runs"
# 執(zhí)行原始函數(shù)
a_function_to_decorate()
# 放一些你希望在原始函數(shù)執(zhí)行后的一些代碼
print "After the function runs"
#在此刻,"a_function_to_decrorate"還沒(méi)有被執(zhí)行,我們返回了創(chuàng)建的封裝函數(shù)
#封裝器包含了函數(shù)以及其前后執(zhí)行的代碼,其已經(jīng)準(zhǔn)備完畢
return the_wrapper_around_the_original_function
# 現(xiàn)在想象下,你創(chuàng)建了一個(gè)你永遠(yuǎn)也不遠(yuǎn)再次接觸的函數(shù)
def a_stand_alone_function() :
print "I am a stand alone function, don't you dare modify me"
a_stand_alone_function()
#輸出: I am a stand alone function, don't you dare modify me
# 好了,你可以封裝它實(shí)現(xiàn)行為的擴(kuò)展。可以簡(jiǎn)單的把它丟給裝飾器
# 裝飾器將動(dòng)態(tài)地把它和你要的代碼封裝起來(lái),并且返回一個(gè)新的可用的函數(shù)。
a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function_decorated()
#輸出 :
#Before the function runs
#I am a stand alone function, don't you dare modify me
#After the function runs
現(xiàn)在你也許要求當(dāng)每次調(diào)用a_stand_alone_function時(shí),實(shí)際調(diào)用卻是a_stand_alone_function_decorated。實(shí)現(xiàn)也很簡(jiǎn)單,可以用my_shiny_new_decorator來(lái)給a_stand_alone_function重新賦值。
a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function()
#輸出 :
#Before the function runs
#I am a stand alone function, don't you dare modify me
#After the function runs
# And guess what, that's EXACTLY what decorators do !
裝飾器揭秘前面的例子,我們可以使用裝飾器的語(yǔ)法:
@my_shiny_new_decorator
def another_stand_alone_function() :
print "Leave me alone"
another_stand_alone_function()
#輸出 :
#Before the function runs
#Leave me alone
#After the function runs
當(dāng)然你也可以累積裝飾:
def bread(func) :
def wrapper() :
print "</''''''/>"
func()
print "</______/>"
return wrapper
def ingredients(func) :
def wrapper() :
print "#tomatoes#"
func()
print "~salad~"
return wrapper
def sandwich(food="--ham--") :
print food
sandwich()
#輸出 : --ham--
sandwich = bread(ingredients(sandwich))
sandwich()
#outputs :
#</''''''/>
# #tomatoes#
# --ham--
# ~salad~
#</______/>
使用python裝飾器語(yǔ)法:
@bread
@ingredients
def sandwich(food="--ham--") :
print food
sandwich()
#輸出 :
#</''''''/>
# #tomatoes#
# --ham--
# ~salad~
#</______/>
裝飾器的順序很重要,需要注意:
@ingredients
@bread
def strange_sandwich(food="--ham--") :
print food
strange_sandwich()
#輸出 :
##tomatoes#
#</''''''/>
# --ham--
#</______/>
# ~salad~
最后回答前面提到的問(wèn)題:
# 裝飾器makebold用于轉(zhuǎn)換為粗體
def makebold(fn):
# 結(jié)果返回該函數(shù)
def wrapper():
# 插入一些執(zhí)行前后的代碼
return "<b>" + fn() + "</b>"
return wrapper
# 裝飾器makeitalic用于轉(zhuǎn)換為斜體
def makeitalic(fn):
# 結(jié)果返回該函數(shù)
def wrapper():
# 插入一些執(zhí)行前后的代碼
return "<i>" + fn() + "</i>"
return wrapper
@makebold
@makeitalic
def say():
return "hello"
print say()
#輸出: <b><i>hello</i></b>
# 等同于
def say():
return "hello"
say = makebold(makeitalic(say))
print say()
#輸出: <b><i>hello</i></b>
內(nèi)置的裝飾器內(nèi)置的裝飾器有三個(gè),分別是staticmethod、classmethod和property,作用分別是把類(lèi)中定義的實(shí)例方法變成靜態(tài)方法、類(lèi)方法和類(lèi)屬性。由于模塊里可以定義函數(shù),所以靜態(tài)方法和類(lèi)方法的用處并不是太多,除非你想要完全的面向?qū)ο缶幊?。而屬性也不是不可或缺的,Java沒(méi)有屬性也一樣活得很滋潤(rùn)。從我個(gè)人的Python經(jīng)驗(yàn)來(lái)看,我沒(méi)有使用過(guò)property,使用staticmethod和classmethod的頻率也非常低。
class Rabbit(object):
def __init__(self, name):
self._name = name
@staticmethod
def newRabbit(name):
return Rabbit(name)
@classmethod
def newRabbit2(cls):
return Rabbit('')
@property
def name(self):
return self._name
這里定義的屬性是一個(gè)只讀屬性,如果需要可寫(xiě),則需要再定義一個(gè)setter:
@name.setter
def name(self, name):
self._name = name
functools模塊functools模塊提供了兩個(gè)裝飾器。這個(gè)模塊是Python 2.5后新增的,一般來(lái)說(shuō)大家用的應(yīng)該都高于這個(gè)版本。但我平時(shí)的工作環(huán)境是2.4 T-T
2.3.1. wraps(wrapped[, assigned][, updated]):
這是一個(gè)很有用的裝飾器??催^(guò)前一篇反射的朋友應(yīng)該知道,函數(shù)是有幾個(gè)特殊屬性比如函數(shù)名,在被裝飾后,上例中的函數(shù)名foo會(huì)變成包裝函數(shù)的名字wrapper,如果你希望使用反射,可能會(huì)導(dǎo)致意外的結(jié)果。這個(gè)裝飾器可以解決這個(gè)問(wèn)題,它能將裝飾過(guò)的函數(shù)的特殊屬性保留。
import time
import functools
def timeit(func):
@functools.wraps(func)
def wrapper():
start = time.clock()
func()
end =time.clock()
print 'used:', end - start
return wrapper
@timeit
def foo():
print 'in foo()'
foo()
print foo.__name__
首先注意第5行,如果注釋這一行,foo.__name__將是'wrapper'。另外相信你也注意到了,這個(gè)裝飾器竟然帶有一個(gè)參數(shù)。實(shí)際上,他還有另外兩個(gè)可選的參數(shù),assigned中的屬性名將使用賦值的方式替換,而updated中的屬性名將使用update的方式合并,你可以通過(guò)查看functools的源代碼獲得它們的默認(rèn)值。對(duì)于這個(gè)裝飾器,相當(dāng)于wrapper = functools.wraps(func)(wrapper)。2.3.2. total_ordering(cls):
這個(gè)裝飾器在特定的場(chǎng)合有一定用處,但是它是在Python 2.7后新增的。它的作用是為實(shí)現(xiàn)了至少__lt__、__le__、__gt__、__ge__其中一個(gè)的類(lèi)加上其他的比較方法,這是一個(gè)類(lèi)裝飾器。如果覺(jué)得不好理解,不妨仔細(xì)看看這個(gè)裝飾器的源代碼:
def total_ordering(cls):
"""Class decorator that fills in missing ordering methods"""
convert = {
'__lt__': [('__gt__', lambda self, other: other < self),
('__le__', lambda self, other: not other < self),
('__ge__', lambda self, other: not self < other)],
'__le__': [('__ge__', lambda self, other: other <= self),
('__lt__', lambda self, other: not other <= self),
('__gt__', lambda self, other: not self <= other)],
'__gt__': [('__lt__', lambda self, other: other > self),
('__ge__', lambda self, other: not other > self),
('__le__', lambda self, other: not self > other)],
'__ge__': [('__le__', lambda self, other: other >= self),
('__gt__', lambda self, other: not other >= self),
('__lt__', lambda self, other: not self >= other)]
}
roots = set(dir(cls)) & set(convert)
if not roots:
raise ValueError('must define at least one ordering operation: < > <= >=')
root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__
for opname, opfunc in convert[root]:
if opname not in roots:
opfunc.__name__ = opname
opfunc.__doc__ = getattr(int, opname).__doc__
setattr(cls, opname, opfunc)
return cls
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。