這里還是先由stackoverflow上面的一個問題引起吧,如果使用如下的代碼:
代碼如下:
@makebold
@makeitalic
def say():
return "Hello"
Hello
你會怎么做?最后給出的答案是:
代碼如下:
def makebold(fn):
def wrapped():
return "" + fn() + ""
return wrapped
def makeitalic(fn):
def wrapped():
return "" + fn() + ""
return wrapped
@makebold
@makeitalic
def hello():
return "hello world"
print hello() ## 返回 hello world
代碼如下:
def foo():
print 'in foo()'
foo()
代碼如下:
import time
def foo():
start = time.clock()
print 'in foo()'
end = time.clock()
print 'used:', end - start
foo()
怎么辦呢?如果把以上新增加的代碼復制到foo2里,這就犯了大忌了~復制什么的難道不是最討厭了么!而且,如果B君繼續看了其他的函數呢?
1.2. 以不變應萬變,是變也
還記得嗎,函數在Python中是一等公民,那么我們可以考慮重新定義一個函數timeit,將foo的引用傳遞給他,然后在timeit中調用foo并進行計時,這樣,我們就達到了不改動foo定義的目的,而且,不論B君看了多少個函數,我們都不用去修改函數定義了!
代碼如下:
import time
def foo():
print 'in foo()'
def timeit(func):
start = time.clock()
func()
end =time.clock()
print 'used:', end - start
timeit(foo)
1.3. 最大限度地少改動!
既然如此,我們就來想想辦法不修改調用的代碼;如果不修改調用代碼,也就意味著調用foo()需要產生調用timeit(foo)的效果。我們可以想到將timeit賦值給foo,但是timeit似乎帶有一個參數……想辦法把參數統一吧!如果timeit(foo)不是直接產生調用效果,而是返回一個與foo參數列表一致的函數的話……就很好辦了,將timeit(foo)的返回值賦值給foo,然后,調用foo()的代碼完全不用修改!
代碼如下:
#-*- coding: UTF-8 -*-
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帶有參數和有返回值的情況,完善它的重任就交給你了 :)
上面這段代碼看起來似乎已經不能再精簡了,Python于是提供了一個語法糖來降低字符輸入量。
代碼如下:
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()
要理解python的裝飾器,我們首先必須明白在Python中函數也是被視為對象。這一點很重要。先看一個例子:
代碼如下:
def shout(word="yes") :
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 !'
代碼如下:
def talk() :
# 你可以在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 getTalk(type="shout") :
# 我們定義另外一個函數
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
#輸出 :
# 該對象由函數返回的其中一個對象:
print talk()
# 或者你可以直接如下調用 :
print getTalk("whisper")()
#輸出 : yes...
代碼如下:
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 !
手工裝飾
那么如何進行手動裝飾呢?
代碼如下:
# 裝飾器是一個函數,而其參數為另外一個函數
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 = 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 !
前面的例子,我們可以使用裝飾器的語法:
代碼如下:
@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
代碼如下:
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~
#<\______/>
代碼如下:
@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~
代碼如下:
# 裝飾器makebold用于轉換為粗體
def makebold(fn):
# 結果返回該函數
def wrapper():
# 插入一些執行前后的代碼
return "" + fn() + ""
return wrapper
# 裝飾器makeitalic用于轉換為斜體
def makeitalic(fn):
# 結果返回該函數
def wrapper():
# 插入一些執行前后的代碼
return "" + fn() + ""
return wrapper
@makebold
@makeitalic
def say():
return "hello"
print say()
#輸出: hello
# 等同于
def say():
return "hello"
say = makebold(makeitalic(say))
print say()
#輸出: hello
內置的裝飾器有三個,分別是staticmethod、classmethod和property,作用分別是把類中定義的實例方法變成靜態方法、類方法和類屬性。由于模塊里可以定義函數,所以靜態方法和類方法的用處并不是太多,除非你想要完全的面向對象編程。而屬性也不是不可或缺的,Java沒有屬性也一樣活得很滋潤。從我個人的Python經驗來看,我沒有使用過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
代碼如下:
@name.setter
def name(self, name):
self._name = name
functools模塊提供了兩個裝飾器。這個模塊是Python 2.5后新增的,一般來說大家用的應該都高于這個版本。但我平時的工作環境是2.4 T-T
2.3.1. wraps(wrapped[, assigned][, updated]):
這是一個很有用的裝飾器。看過前一篇反射的朋友應該知道,函數是有幾個特殊屬性比如函數名,在被裝飾后,上例中的函數名foo會變成包裝函數的名字wrapper,如果你希望使用反射,可能會導致意外的結果。這個裝飾器可以解決這個問題,它能將裝飾過的函數的特殊屬性保留。
代碼如下:
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__
2.3.2. total_ordering(cls):
這個裝飾器在特定的場合有一定用處,但是它是在Python 2.7后新增的。它的作用是為實現了至少__lt__、__le__、__gt__、__ge__其中一個的類加上其他的比較方法,這是一個類裝飾器。如果覺得不好理解,不妨仔細看看這個裝飾器的源代碼:
代碼如下:
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
希望本文所述對大家的Python程序設計有所幫助。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com