若是做为一个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): ....
记住这个特殊的语法,后面咱们会展现这个强大的语法糖