python裝飾器(披着羊皮的狼)

python裝飾器的做用是在不改變原有函數的基礎上,對函數的功能進行增長或者修改。python

裝飾器語法是python語言更加優美且避免不少繁瑣的事情,flask中配置路由的方式即是裝飾器。flask

首先python中一個函數也是能夠當作一個對象進行傳遞的。函數

 1 def sheep(f):
 2     def she():
 3         print("I'm a sheep")
 4         return f()
 5     return she
 6 
 7 @sheep
 8 def wolf():
 9     print("I'm a wolf")
10 
11 if __name__ == "__main__":
12     wolf()

輸出結果爲spa

I'm a sheep
I'm a wolf

上面代碼至關於 code

wolf = sheep(wolf)
wolf()

帶參數的裝飾器orm

 1 def change(a):
 2     def sheep(f):
 3         def she():
 4             print("I'm a sheep")
 5             f()
 6             print("you're not ,you're {} sheep".format(a))
 7         return she
 8     return sheep
 9 
10 @change("fake")
11 def wolf():
12     print("I'm a wolf")
13 
14 if __name__ == "__main__":
15     wolf()

結果:對象

I'm a sheep
I'm a wolf
you're not ,you're fake sheep

至關於blog

wolf = change("fake")(wolf)
wolf()

其實函數名此時發生了改變路由

wolf.__name__的值爲sheform

解決辦法爲使用functools.wraps

 1 import functools
 2 
 3 def change(a):
 4     def sheep(f):
 5         @functools.wraps(f)
 6         def she():
 7             print("I'm a sheep")
 8             f()
 9             print("you're not ,you're {} sheep".format(a))
10         return she
11     return sheep
12 
13 def wolf():
14     print("I'm a wolf")
15 
16 if __name__ == "__main__":
17     wolf = change("fake")(wolf)
18     wolf()
相關文章
相關標籤/搜索