若是做爲一個Python入門,不瞭解Python裝飾器也沒什麼,可是若是做爲一箇中級Python開發人員,若是再不對python裝飾器熟稔於心的話,那麼可能並無量變積累到質變。html
我之前也看過不少講python 裝飾器的文章,可是都是看了就忘。一方面是沒有作太多的練習,二是對它的領會不是很深。python
但願引覺得戒!!!設計模式
若是你瞭解Java,你確定聽過 裝飾器模式。在面向對象中,裝飾模式指:動態地給一個對象添加一些額外的職責。就增長一些功能來講,裝飾模式比生成子類更爲靈活。app
在設計模式學習----裝飾器模式,我摘取了下面一段使用裝飾器模式的代碼函數
public class DecoratorPattern { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Basket basket = new Original(); //一個裝飾的過程 Basket myBasket =new AppleDecorator(new BananaDecorator(new OrangeDecorator(basket))); myBasket.show(); } }
等會注意下 Basket myBasket =new AppleDecorator(new BananaDecorator(new OrangeDecorator(basket)))
這段的寫法學習
在Python官方文檔PythonDecorators 是這麼介紹裝飾器的翻譯
What is a DecoratorA decorator is the name used for a software design pattern. Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated.設計
翻一下: 就是裝飾器是一種軟件設計模式,被用來動態修改函數、方法,或者類功能卻不是經過子類,或者修改原代碼實現。code
跟以前是一個意思!!!htm
而Python的裝飾器與之不一樣,官方這麼說:
The "decorators" we talk about with concern to Python are not exactly the same thing as the DecoratorPattern described above. A Python decorator is a specific change to the Python syntax that allows us to more conveniently alter functions and methods (and possibly classes in a future version). This supports more readable applications of the DecoratorPattern but also other uses as well.Support for the decorator syntax was proposed for Python in PEP 318, and will be implemented in Python 2.4.
翻譯下:Python的 decorators 與 DecoratorPattern並不徹底相同。 Python的decorator是一種特殊:在語法上實現容許咱們更靈活地更改方法,或者函數。
例子:
@classmethod def foo (arg1, arg2): ....
記住這個特殊的語法,後面咱們會展現這個強大的語法糖