浅析Python装饰器以及装饰器模式

yipeiwu_com5年前Python基础

漫谈

如果作为一个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是一种特殊:在语法上实现允许我们更灵活地更改方法,或者函数。

例子:

@classmethod
def foo (arg1, arg2):
  ....

记住这个特殊的语法,后面我们会展示这个强大的语法糖

相关文章

Python比较文件夹比另一同名文件夹多出的文件并复制出来的方法

Python比较文件夹比另一同名文件夹多出的文件并复制出来的方法

本文实例讲述了Python比较文件夹比另一同名文件夹多出的文件并复制出来的方法。分享给大家供大家参考。具体如下: 这个东东本来是做来给公司数据同步用的:新服务器还没正式启用,旧的服务器还...

Python过滤函数filter()使用自定义函数过滤序列实例

filter函数: filter()函数可以对序列做过滤处理,就是说可以使用一个自定的函数过滤一个序列,把序列的每一项传到自定义的过滤函数里处理,并返回结果做过滤。最终一次性返回过滤后的...

Django中使用MySQL5.5的教程

Django中使用MySQL5.5的教程

“MySQL是一个功能齐全的关系数据库管理系统(RDBMS),可以与Oracle DB和Microsoft的SQL Server竞争。MySQL由瑞典公司MySQL AB赞助,该公司由O...

Python实现的文本对比报告生成工具示例

Python实现的文本对比报告生成工具示例

本文实例讲述了Python实现的文本对比报告生成工具。分享给大家供大家参考,具体如下: 借助于difflib的功能,可以针对我们的使用情况进一步进行功能的聚合。我想要的功能是输入两个文件...

Python批量更改文件名的实现方法

Python批量更改文件名的实现方法 前言: 由于后台数据有好多,但是文案提供过来的图片命名全部没有按照格式来命名,Python这么强大的语言,肯定是能够处理这个问题的,于是我就写了一个...