怎麼作才能讓一個函數同時用兩個裝飾器,像下面這樣:html
@makebold @makeitalic def say(): return "Hello"
我但願獲得python
<b><i>Hello</i></b>
我只是想知道裝飾器怎麼工做的!git
去看看文檔,答在下面:設計模式
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() ## returns <b><i>hello world</i></b>
若是你不想看詳細的解釋的話請看上面那個答案.api
要了解裝飾器,你必須瞭解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!'
好了,先記住上面的,一會還會用到.app
Python函數另外一個有趣的特性就是你能夠在一個函數裏定義另外一個函數!dom
def talk(): # 你能夠在"talk"裏定義另外一個函數 ... def whisper(word="yes"): return word.lower()+"..." # 讓咱們用用它! print whisper() # 每次調用"talk"時都會定義一次"whisper",而後"talk"會調用"whisper" talk() # 輸出: # "yes..." # 可是在"talk"意外"whisper"是不存在的: try: print whisper() except NameError, e: print e #輸出 : "name 'whisper' is not defined"*
好,終於到了有趣的地方了...異步
已經知道函數就是對象.所以,對象:函數
這就意味着函數能夠返回另外一個函數.來看看!☺
def getTalk(kind="shout"): # 在函數裏定義一個函數 def shout(word="yes"): return word.capitalize()+"!" def whisper(word="yes") : return word.lower()+"..."; # 返回一個函數 if kind == "shout": # 這裏不用"()",咱們不是要調用函數 # 只是返回函數對象 return shout else: return whisper # 怎麼用這個特性呢? # 把函數賦值給變量 talk = getTalk() # 能夠看到"talk"是一個函數對象 print talk # 輸出 : <function shout at 0xb7ea817c> # 函數返回的是對象: print talk() # 輸出 : Yes! # 不嫌麻煩你也能夠這麼用 print getTalk("whisper")() # 輸出 : yes...
既然能夠return
一個函數, 你也能夠在把函數做爲參數傳遞:
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!
學習裝飾器的基本知識都在上面了.裝飾器就是"wrappers",它可讓你在你裝飾函數以前或以後執行程序,而不用修改函數自己.
怎麼樣本身作呢:
# 裝飾器就是把其餘函數做爲參數的函數 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_decorate" 函數永遠不會被執行 # 在這裏返回剛纔包裝過的函數 # 在包裝函數裏包含要在原始函數先後執行的代碼. 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() #輸出s: #Before the function runs #I am a stand alone function, don't you dare modify me #After the function runs
如今,你或許每次都想用a_stand_alone_function_decorated
代替a_stand_alone_function
,很簡單,只須要用my_shiny_new_decorator
返回的函數重寫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 # 想到了嗎,這就是裝飾器乾的事!
用上一個例子,看看裝飾器的語法:
@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
就這麼簡單.@decorator
就是下面的簡寫:
another_stand_alone_function = my_shiny_new_decorator(another_stand_alone_function)
裝飾器就是 decorator design pattern的pythonic的變種.在Python中有許多經典的設計模式來知足開發者.
固然,你也能夠本身寫裝飾器:
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() #outputs: --ham-- sandwich = bread(ingredients(sandwich)) sandwich() #outputs: #</''''''\> # #tomatoes# # --ham-- # ~salad~ #<\______/>
用Python裝飾器語法糖:
@bread @ingredients def sandwich(food="--ham--"): print food sandwich() #outputs: #</''''''\> # #tomatoes# # --ham-- # ~salad~ #<\______/>
改變一下順序:
@ingredients @bread def strange_sandwich(food="--ham--"): print food strange_sandwich() #outputs: ##tomatoes# #</''''''\> # --ham-- #<\______/> # ~salad~
做爲結論,相信你如今已經知道答案了:
# 字體變粗裝飾器 def makebold(fn): # 裝飾器將返回新的函數 def wrapper(): # 在以前或者以後插入新的代碼 return "<b>" + fn() + "</b>" return wrapper # 斜體裝飾器 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>
別輕鬆太早,看看下面的高級用法
# 這不是什麼黑魔法,你只須要讓包裝器傳遞參數: def a_decorator_passing_arguments(function_to_decorate): def a_wrapper_accepting_arguments(arg1, arg2): print "I got args! Look:", arg1, arg2 function_to_decorate(arg1, arg2) return a_wrapper_accepting_arguments # 當你調用裝飾器返回的函數時,也就調用了包裝器,把參數傳入包裝器裏, # 它將把參數傳遞給被裝飾的函數裏. @a_decorator_passing_arguments def print_full_name(first_name, last_name): print "My name is", first_name, last_name print_full_name("Peter", "Venkman") # 輸出: #I got args! Look: Peter Venkman #My name is Peter Venkman
在Python裏方法和函數幾乎同樣.惟一的區別就是方法的第一個參數是一個當前對象的(self
)
也就是說你能夠用一樣的方式來裝飾方法!只要記得把self
加進去:
def method_friendly_decorator(method_to_decorate): def wrapper(self, lie): lie = lie - 3 # 女性福音 :-) return method_to_decorate(self, lie) return wrapper class Lucy(object): def __init__(self): self.age = 32 @method_friendly_decorator def sayYourAge(self, lie): print "I am %s, what did you think?" % (self.age + lie) l = Lucy() l.sayYourAge(-3) #輸出: I am 26, what did you think?
若是你想造一個更通用的能夠同時知足方法和函數的裝飾器,用*args,**kwargs
就能夠了
def a_decorator_passing_arbitrary_arguments(function_to_decorate): # 包裝器接受全部參數 def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs): print "Do I have args?:" print args print kwargs # 如今把*args,**kwargs解包 # 若是你不明白什麼是解包的話,請查閱: # http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/ function_to_decorate(*args, **kwargs) return a_wrapper_accepting_arbitrary_arguments @a_decorator_passing_arbitrary_arguments def function_with_no_argument(): print "Python is cool, no argument here." function_with_no_argument() #輸出 #Do I have args?: #() #{} #Python is cool, no argument here. @a_decorator_passing_arbitrary_arguments def function_with_arguments(a, b, c): print a, b, c function_with_arguments(1,2,3) #輸出 #Do I have args?: #(1, 2, 3) #{} #1 2 3 @a_decorator_passing_arbitrary_arguments def function_with_named_arguments(a, b, c, platypus="Why not ?"): print "Do %s, %s and %s like platypus? %s" %\ (a, b, c, platypus) function_with_named_arguments("Bill", "Linus", "Steve", platypus="Indeed!") #輸出 #Do I have args ? : #('Bill', 'Linus', 'Steve') #{'platypus': 'Indeed!'} #Do Bill, Linus and Steve like platypus? Indeed! class Mary(object): def __init__(self): self.age = 31 @a_decorator_passing_arbitrary_arguments def sayYourAge(self, lie=-3): # 能夠加入一個默認值 print "I am %s, what did you think ?" % (self.age + lie) m = Mary() m.sayYourAge() #輸出 # Do I have args?: #(<__main__.Mary object at 0xb7d303ac>,) #{} #I am 28, what did you think?
好了,如何把參數傳遞給裝飾器本身?
由於裝飾器必須接收一個函數當作參數,因此有點麻煩.好吧,你不能夠直接把被裝飾函數的參數傳遞給裝飾器.
在咱們考慮這個問題時,讓咱們從新回顧下:
# 裝飾器就是一個'日常不過'的函數 def my_decorator(func): print "I am an ordinary function" def wrapper(): print "I am function returned by the decorator" func() return wrapper # 所以你能夠不用"@"也能夠調用他 def lazy_function(): print "zzzzzzzz" decorated_function = my_decorator(lazy_function) #輸出: I am an ordinary function # 之因此輸出 "I am an ordinary function"是由於你調用了函數, # 並不是什麼魔法. @my_decorator def lazy_function(): print "zzzzzzzz" #輸出: I am an ordinary function
看見了嗎,和"my_decorator
"同樣只是被調用.因此當你用@my_decorator
你只是告訴Python去掉用被變量my_decorator
標記的函數.
這很是重要!你的標記能直接指向裝飾器.
讓咱們作點邪惡的事.☺
def decorator_maker(): print "I make decorators! I am executed only once: "+\ "when you make me create a decorator." def my_decorator(func): print "I am a decorator! I am executed only when you decorate a function." def wrapped(): print ("I am the wrapper around the decorated function. " "I am called when you call the decorated function. " "As the wrapper, I return the RESULT of the decorated function.") return func() print "As the decorator, I return the wrapped function." return wrapped print "As a decorator maker, I return a decorator" return my_decorator # 讓咱們建一個裝飾器.它只是一個新函數. new_decorator = decorator_maker() #輸出: #I make decorators! I am executed only once: when you make me create a decorator. #As a decorator maker, I return a decorator # 下面來裝飾一個函數 def decorated_function(): print "I am the decorated function." decorated_function = new_decorator(decorated_function) #輸出: #I am a decorator! I am executed only when you decorate a function. #As the decorator, I return the wrapped function # Let’s call the function: decorated_function() #輸出: #I am the wrapper around the decorated function. I am called when you call the decorated function. #As the wrapper, I return the RESULT of the decorated function. #I am the decorated function.
一點都不難把.
下面讓咱們去掉全部可惡的中間變量:
def decorated_function(): print "I am the decorated function." decorated_function = decorator_maker()(decorated_function) #輸出: #I make decorators! I am executed only once: when you make me create a decorator. #As a decorator maker, I return a decorator #I am a decorator! I am executed only when you decorate a function. #As the decorator, I return the wrapped function. # 最後: decorated_function() #輸出: #I am the wrapper around the decorated function. I am called when you call the decorated function. #As the wrapper, I return the RESULT of the decorated function. #I am the decorated function.
讓咱們簡化一下:
@decorator_maker() def decorated_function(): print "I am the decorated function." #輸出: #I make decorators! I am executed only once: when you make me create a decorator. #As a decorator maker, I return a decorator #I am a decorator! I am executed only when you decorate a function. #As the decorator, I return the wrapped function. #最終: decorated_function() #輸出: #I am the wrapper around the decorated function. I am called when you call the decorated function. #As the wrapper, I return the RESULT of the decorated function. #I am the decorated function.
看到了嗎?咱們用一個函數調用"@
"語法!:-)
因此讓咱們回到裝飾器的.若是咱們在函數運行過程當中動態生成裝飾器,咱們是否是能夠把參數傳遞給函數?
def decorator_maker_with_arguments(decorator_arg1, decorator_arg2): print "I make decorators! And I accept arguments:", decorator_arg1, decorator_arg2 def my_decorator(func): # 這裏傳遞參數的能力是借鑑了 closures. # 若是對closures感到困惑能夠看看下面這個: # http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python print "I am the decorator. Somehow you passed me arguments:", decorator_arg1, decorator_arg2 # 不要忘了裝飾器參數和函數參數! def wrapped(function_arg1, function_arg2) : print ("I am the wrapper around the decorated function.\n" "I can access all the variables\n" "\t- from the decorator: {0} {1}\n" "\t- from the function call: {2} {3}\n" "Then I can pass them to the decorated function" .format(decorator_arg1, decorator_arg2, function_arg1, function_arg2)) return func(function_arg1, function_arg2) return wrapped return my_decorator @decorator_maker_with_arguments("Leonard", "Sheldon") def decorated_function_with_arguments(function_arg1, function_arg2): print ("I am the decorated function and only knows about my arguments: {0}" " {1}".format(function_arg1, function_arg2)) decorated_function_with_arguments("Rajesh", "Howard") #輸出: #I make decorators! And I accept arguments: Leonard Sheldon #I am the decorator. Somehow you passed me arguments: Leonard Sheldon #I am the wrapper around the decorated function. #I can access all the variables # - from the decorator: Leonard Sheldon # - from the function call: Rajesh Howard #Then I can pass them to the decorated function #I am the decorated function and only knows about my arguments: Rajesh Howard
好了,上面就是帶參數的裝飾器.參數能夠設置成變量:
c1 = "Penny" c2 = "Leslie" @decorator_maker_with_arguments("Leonard", c1) def decorated_function_with_arguments(function_arg1, function_arg2): print ("I am the decorated function and only knows about my arguments:" " {0} {1}".format(function_arg1, function_arg2)) decorated_function_with_arguments(c2, "Howard") #輸出: #I make decorators! And I accept arguments: Leonard Penny #I am the decorator. Somehow you passed me arguments: Leonard Penny #I am the wrapper around the decorated function. #I can access all the variables # - from the decorator: Leonard Penny # - from the function call: Leslie Howard #Then I can pass them to the decorated function #I am the decorated function and only knows about my arguments: Leslie Howard
你能夠用這個小技巧把任何函數的參數傳遞給裝飾器.若是你願意還能夠用*args,**kwargs
.可是必定要記住了裝飾器只能被調用一次.當Python載入腳本後,你不能夠動態的設置參數了.當你運行import x
,函數已經被裝飾,因此你什麼都不能動了.
好吧,做爲獎勵,我就給你講講如何怎麼讓全部的裝飾器接收任何參數.爲了接收參數,咱們用另外的函數來建咱們的裝飾器.
咱們包裝裝飾器.
還有什麼咱們能夠看到嗎?
對了,裝飾器!
讓咱們來爲裝飾器一個裝飾器:
def decorator_with_args(decorator_to_enhance): """ 這個函數將被用來做爲裝飾器. 它必須去裝飾要成爲裝飾器的函數. 休息一下. 它將容許全部的裝飾器能夠接收任意數量的參數,因此之後你沒必要爲每次都要作這個頭疼了. saving you the headache to remember how to do that every time. """ # 咱們用傳遞參數的一樣技巧. def decorator_maker(*args, **kwargs): # 咱們動態的創建一個只接收一個函數的裝飾器, # 可是他能接收來自maker的參數 def decorator_wrapper(func): # 最後咱們返回原始的裝飾器,畢竟它只是'日常'的函數 # 惟一的陷阱:裝飾器必須有這個特殊的,不然將不會奏效. return decorator_to_enhance(func, *args, **kwargs) return decorator_wrapper
下面是如何用它們:
# 下面的函數是你建來當裝飾器用的,而後把裝飾器加到上面:-) # 不要忘了這個 "decorator(func, *args, **kwargs)" @decorator_with_args def decorated_decorator(func, *args, **kwargs): def wrapper(function_arg1, function_arg2): print "Decorated with", args, kwargs return func(function_arg1, function_arg2) return wrapper # 如今你用你本身的裝飾裝飾器來裝飾你的函數(汗~~~) @decorated_decorator(42, 404, 1024) def decorated_function(function_arg1, function_arg2): print "Hello", function_arg1, function_arg2 decorated_function("Universe and", "everything") #輸出: #Decorated with (42, 404, 1024) {} #Hello Universe and everything # Whoooot!
估計你看到這和你剛看完愛因斯坦相對論差很少,可是如今若是明白怎麼用就好多了吧.
functools
模塊在2.5被引進.它包含了一個functools.wraps()
函數,能夠複製裝飾器函數的名字,模塊和文檔給它的包裝器.
(事實上:functools.wraps()
是一個裝飾器!☺)
#爲了debug,堆棧跟蹤將會返回函數的 __name__ def foo(): print "foo" print foo.__name__ #輸出: foo # 若是加上裝飾器,將變得有點複雜 def bar(func): def wrapper(): print "bar" return func() return wrapper @bar def foo(): print "foo" print foo.__name__ #輸出: wrapper # "functools" 將有所幫助 import functools def bar(func): # 咱們所說的"wrapper",正在包裝 "func", # 好戲開始了 @functools.wraps(func) def wrapper(): print "bar" return func() return wrapper @bar def foo(): print "foo" print foo.__name__ #輸出: foo
如今遇到了大問題:咱們用裝飾器幹什麼?
看起來很黃很暴力,可是若是有實際用途就更好了.好了這裏有1000個用途.傳統的用法就是用它來爲外部的庫的函數(你不能修改的)作擴展,或者debug(你不想修改它,由於它是暫時的).
你也能夠用DRY的方法去擴展一些函數,像:
def benchmark(func): """ A decorator that prints the time a function takes to execute. """ import time def wrapper(*args, **kwargs): t = time.clock() res = func(*args, **kwargs) print func.__name__, time.clock()-t return res return wrapper def logging(func): """ A decorator that logs the activity of the script. (it actually just prints it, but it could be logging!) """ def wrapper(*args, **kwargs): res = func(*args, **kwargs) print func.__name__, args, kwargs return res return wrapper def counter(func): """ A decorator that counts and prints the number of times a function has been executed """ def wrapper(*args, **kwargs): wrapper.count = wrapper.count + 1 res = func(*args, **kwargs) print "{0} has been used: {1}x".format(func.__name__, wrapper.count) return res wrapper.count = 0 return wrapper @counter @benchmark @logging def reverse_string(string): return str(reversed(string)) print reverse_string("Able was I ere I saw Elba") print reverse_string("A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!") #輸出: #reverse_string ('Able was I ere I saw Elba',) {} #wrapper 0.0 #wrapper has been used: 1x #ablE was I ere I saw elbA #reverse_string ('A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!',) {} #wrapper 0.0 #wrapper has been used: 2x #!amanaP :lanac a ,noep a ,stah eros ,raj a ,hsac ,oloR a ,tur a ,mapS ,snip ,eperc a ,)lemac a ro( niaga gab ananab a ,gat a ,nat a ,gab ananab a ,gag a ,inoracam ,elacrep ,epins ,spam ,arutaroloc a ,shajar ,soreh ,atsap ,eonac a ,nalp a ,nam A
固然,裝飾器的好處就是你能夠用它們來作任何事而不用重寫,DRY:
@counter @benchmark @logging def get_random_futurama_quote(): from urllib import urlopen result = urlopen("http://subfusion.net/cgi-bin/quote.pl?quote=futurama").read() try: value = result.split("<br><b><hr><br>")[1].split("<br><br><hr>")[0] return value.strip() except: return "No, I'm ... doesn't!" print get_random_futurama_quote() print get_random_futurama_quote() #輸出: #get_random_futurama_quote () {} #wrapper 0.02 #wrapper has been used: 1x #The laws of science be a harsh mistress. #get_random_futurama_quote () {} #wrapper 0.01 #wrapper has been used: 2x #Curse you, merciful Poseidon!
Python自身提供了幾個裝飾器,像property
, staticmethod
.
好大的坑!