本文實例講述了Python中的裝飾器用法。分享給大家供大家參考。具體分析如下:
這里還是先由stackoverflow上面的一個問題引起吧,如果使用如下的代碼:
@makeitalic
def say():
return "Hello"
打印出如下的輸出:
<b><i>Hello<i></b>
你會怎么做?最后給出的答案是:
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>
現在我們來看看如何從一些最基礎的方式來理解Python的裝飾器。
裝飾器是一個很著名的設計模式,經常被用于有切面需求的場景,較為經典的有插入日志、性能測試、事務處理等。裝飾器是解決這類問題的絕佳設計,有了裝飾器,我們就可以抽離出大量函數中與函數功能本身無關的雷同代碼并繼續重用。概括的講,裝飾器的作用就是為已經存在的對象添加額外的功能。
1.1. 需求是怎么來的?
裝飾器的定義很是抽象,我們來看一個小例子。
print 'in foo()'
foo()
這是一個很無聊的函數沒錯。但是突然有一個更無聊的人,我們稱呼他為B君,說我想看看執行這個函數用了多長時間,好吧,那么我們可以這樣做:
def foo():
start = time.clock()
print 'in foo()'
end = time.clock()
print 'used:', end - start
foo()
很好,功能看起來無懈可擊。可是蛋疼的B君此刻突然不想看這個函數了,他對另一個叫foo2的函數產生了更濃厚的興趣。
怎么辦呢?如果把以上新增加的代碼復制到foo2里,這就犯了大忌了~復制什么的難道不是最討厭了么!而且,如果B君繼續看了其他的函數呢?
1.2. 以不變應萬變,是變也
還記得嗎,函數在Python中是一等公民,那么我們可以考慮重新定義一個函數timeit,將foo的引用傳遞給他,然后在timeit中調用foo并進行計時,這樣,我們就達到了不改動foo定義的目的,而且,不論B君看了多少個函數,我們都不用去修改函數定義了!
def foo():
print 'in foo()'
def timeit(func):
start = time.clock()
func()
end =time.clock()
print 'used:', end - start
timeit(foo)
看起來邏輯上并沒有問題,一切都很美好并且運作正常!……等等,我們似乎修改了調用部分的代碼。原本我們是這樣調用的:foo(),修改以后變成了:timeit(foo)。這樣的話,如果foo在N處都被調用了,你就不得不去修改這N處的代碼。或者更極端的,考慮其中某處調用的代碼無法修改這個情況,比如:這個函數是你交給別人使用的。
1.3. 最大限度地少改動!
既然如此,我們就來想想辦法不修改調用的代碼;如果不修改調用代碼,也就意味著調用foo()需要產生調用timeit(foo)的效果。我們可以想到將timeit賦值給foo,但是timeit似乎帶有一個參數……想辦法把參數統一吧!如果timeit(foo)不是直接產生調用效果,而是返回一個與foo參數列表一致的函數的話……就很好辦了,將timeit(foo)的返回值賦值給foo,然后,調用foo()的代碼完全不用修改!
import time
def foo():
print 'in foo()'
# 定義一個計時器,傳入一個,并返回另一個附加了計時功能的方法
def timeit(func):
# 定義一個內嵌的包裝函數,給傳入的函數加上計時功能的包裝
def wrapper():
start = time.clock()
func()
end =time.clock()
print 'used:', end - start
# 將包裝后的函數返回
return wrapper
foo = timeit(foo)
foo()
這樣,一個簡易的計時器就做好了!我們只需要在定義foo以后調用foo之前,加上foo = timeit(foo),就可以達到計時的目的,這也就是裝飾器的概念,看起來像是foo被timeit裝飾了。在在這個例子中,函數進入和退出時需要計時,這被稱為一個橫切面(Aspect),這種編程方式被稱為面向切面的編程(Aspect-Oriented Programming)。與傳統編程習慣的從上往下執行方式相比較而言,像是在函數執行的流程中橫向地插入了一段邏輯。在特定的業務領域里,能減少大量重復代碼。面向切面編程還有相當多的術語,這里就不多做介紹,感興趣的話可以去找找相關的資料。
這個例子僅用于演示,并沒有考慮foo帶有參數和有返回值的情況,完善它的重任就交給你了 :)
上面這段代碼看起來似乎已經不能再精簡了,Python于是提供了一個語法糖來降低字符輸入量。
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()
重點關注第11行的@timeit,在定義上加上這一行與另外寫foo = timeit(foo)完全等價,千萬不要以為@有另外的魔力。除了字符輸入少了一些,還有一個額外的好處:這樣看上去更有裝飾器的感覺。
要理解python的裝飾器,我們首先必須明白在Python中函數也是被視為對象。這一點很重要。先看一個例子:
return word.capitalize()+" !"
print shout()
# 輸出 : 'Yes !'
# 作為一個對象,你可以把函數賦給任何其他對象變量
scream = shout
# 注意我們沒有使用圓括號,因為我們不是在調用函數
# 我們把函數shout賦給scream,也就是說你可以通過scream調用shout
print scream()
# 輸出 : 'Yes !'
# 還有,你可以刪除舊的名字shout,但是你仍然可以通過scream來訪問該函數
del shout
try :
print shout()
except NameError, e :
print e
#輸出 : "name 'shout' is not defined"
print scream()
# 輸出 : 'Yes !'
我們暫且把這個話題放旁邊,我們先看看python另外一個很有意思的屬性:可以在函數中定義函數:
# 你可以在talk中定義另外一個函數
def whisper(word="yes") :
return word.lower()+"...";
# ... 并且立馬使用它
print whisper()
# 你每次調用'talk',定義在talk里面的whisper同樣也會被調用
talk()
# 輸出 :
# yes...
# 但是"whisper" 不會單獨存在:
try :
print whisper()
except NameError, e :
print e
#輸出 : "name 'whisper' is not defined"*
函數引用
從以上兩個例子我們可以得出,函數既然作為一個對象,因此:
1. 其可以被賦給其他變量
2. 其可以被定義在另外一個函數內
這也就是說,函數可以返回一個函數,看下面的例子:
# 我們定義另外一個函數
def shout(word="yes") :
return word.capitalize()+" !"
def whisper(word="yes") :
return word.lower()+"...";
# 然后我們返回其中一個
if type == "shout" :
# 我們沒有使用(),因為我們不是在調用該函數
# 我們是在返回該函數
return shout
else :
return whisper
# 然后怎么使用呢 ?
# 把該函數賦予某個變量
talk = getTalk()
# 這里你可以看到talk其實是一個函數對象:
print talk
#輸出 : <function shout at 0xb7ea817c>
# 該對象由函數返回的其中一個對象:
print talk()
# 或者你可以直接如下調用 :
print getTalk("whisper")()
#輸出 : yes...
還有,既然可以返回一個函數,我們可以把它作為參數傳遞給函數:
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 !
這里你已經足夠能理解裝飾器了,其他它可被視為封裝器。也就是說,它能夠讓你在裝飾前后執行代碼而無須改變函數本身內容。
手工裝飾
那么如何進行手動裝飾呢?
def my_shiny_new_decorator(a_function_to_decorate) :
# 在內部定義了另外一個函數:一個封裝器。
# 這個函數將原始函數進行封裝,所以你可以在它之前或者之后執行一些代碼
def the_wrapper_around_the_original_function() :
# 放一些你希望在真正函數執行前的一些代碼
print "Before the function runs"
# 執行原始函數
a_function_to_decorate()
# 放一些你希望在原始函數執行后的一些代碼
print "After the function runs"
#在此刻,"a_function_to_decrorate"還沒有被執行,我們返回了創建的封裝函數
#封裝器包含了函數以及其前后執行的代碼,其已經準備完畢
return the_wrapper_around_the_original_function
# 現在想象下,你創建了一個你永遠也不遠再次接觸的函數
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
# 好了,你可以封裝它實現行為的擴展。可以簡單的把它丟給裝飾器
# 裝飾器將動態地把它和你要的代碼封裝起來,并且返回一個新的可用的函數。
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
現在你也許要求當每次調用a_stand_alone_function時,實際調用卻是a_stand_alone_function_decorated。實現也很簡單,可以用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 !
裝飾器揭秘
前面的例子,我們可以使用裝飾器的語法:
def another_stand_alone_function() :
print "Leave me alone"
another_stand_alone_function()
#輸出 :
#Before the function runs
#Leave me alone
#After the function runs
當然你也可以累積裝飾:
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裝飾器語法:
@ingredients
def sandwich(food="--ham--") :
print food
sandwich()
#輸出 :
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>
裝飾器的順序很重要,需要注意:
@bread
def strange_sandwich(food="--ham--") :
print food
strange_sandwich()
#輸出 :
##tomatoes#
#</''''''\>
# --ham--
#<\______/>
# ~salad~
最后回答前面提到的問題:
def makebold(fn):
# 結果返回該函數
def wrapper():
# 插入一些執行前后的代碼
return "<b>" + fn() + "</b>"
return wrapper
# 裝飾器makeitalic用于轉換為斜體
def makeitalic(fn):
# 結果返回該函數
def wrapper():
# 插入一些執行前后的代碼
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>
內置的裝飾器
內置的裝飾器有三個,分別是staticmethod、classmethod和property,作用分別是把類中定義的實例方法變成靜態方法、類方法和類屬性。由于模塊里可以定義函數,所以靜態方法和類方法的用處并不是太多,除非你想要完全的面向對象編程。而屬性也不是不可或缺的,Java沒有屬性也一樣活得很滋潤。從我個人的Python經驗來看,我沒有使用過property,使用staticmethod和classmethod的頻率也非常低。
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
這里定義的屬性是一個只讀屬性,如果需要可寫,則需要再定義一個setter:
def name(self, name):
self._name = name
functools模塊
functools模塊提供了兩個裝飾器。這個模塊是Python 2.5后新增的,一般來說大家用的應該都高于這個版本。但我平時的工作環境是2.4 T-T
2.3.1. wraps(wrapped[, assigned][, updated]):
這是一個很有用的裝飾器。看過前一篇反射的朋友應該知道,函數是有幾個特殊屬性比如函數名,在被裝飾后,上例中的函數名foo會變成包裝函數的名字wrapper,如果你希望使用反射,可能會導致意外的結果。這個裝飾器可以解決這個問題,它能將裝飾過的函數的特殊屬性保留。
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'。另外相信你也注意到了,這個裝飾器竟然帶有一個參數。實際上,他還有另外兩個可選的參數,assigned中的屬性名將使用賦值的方式替換,而updated中的屬性名將使用update的方式合并,你可以通過查看functools的源代碼獲得它們的默認值。對于這個裝飾器,相當于wrapper = functools.wraps(func)(wrapper)。
2.3.2. total_ordering(cls):
這個裝飾器在特定的場合有一定用處,但是它是在Python 2.7后新增的。它的作用是為實現了至少__lt__、__le__、__gt__、__ge__其中一個的類加上其他的比較方法,這是一個類裝飾器。如果覺得不好理解,不妨仔細看看這個裝飾器的源代碼:
"""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
希望本文所述對大家的Python程序設計有所幫助。