国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

淺析Python裝飾器以及裝飾器模式

2020-02-15 21:31:22
字體:
來源:轉載
供稿:網友

漫談

如果作為一個Python入門,不了解Python裝飾器也沒什么,但是如果作為一個中級Python開發人員,如果再不對python裝飾器熟稔于心的話,那么可能并沒有量變積累到質變。

我以前也看過很多講python 裝飾器的文章,但是都是看了就忘。一方面是沒有做太多的練習,二是對它的領會不是很深。

希望引以為戒!!!

鄭傳

裝飾模式

如果你了解Java,你肯定聽過 裝飾器模式。在面向對象中,裝飾模式指:動態地給一個對象添加一些額外的職責。就增加一些功能來說,裝飾模式比生成子類更為靈活。

在設計模式學習----裝飾器模式,我摘取了下面一段使用裝飾器模式的代碼

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 Decorator
A 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.

翻一下: 就是裝飾器是一種軟件設計模式,被用來動態修改函數、方法,或者類功能卻不是通過子類,或者修改原代碼實現。

跟之前是一個意思!!!

Python Decorator
而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是一種特殊:在語法上實現允許我們更靈活地更改方法,或者函數。

例子:

@classmethoddef foo (arg1, arg2):  ....

記住這個特殊的語法,后面我們會展示這個強大的語法糖

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 托里县| 庐江县| 望城县| 榕江县| 韩城市| 瑞安市| 滦南县| 耒阳市| 静海县| 牙克石市| 柳林县| 沭阳县| 泗洪县| 霍林郭勒市| 鲁山县| 托克托县| 汤阴县| 雷山县| 台东市| 广安市| 红安县| 仲巴县| 苏尼特左旗| 南充市| 宝坻区| 正镶白旗| 隆回县| 邮箱| 苍南县| 武义县| 垣曲县| 皋兰县| 施秉县| 裕民县| 苏尼特右旗| 津南区| 承德县| 桦川县| 阳山县| 青神县| 梁河县|