A Brief analysis of Python Decorator and decorator pattern

  • 2020-10-07 18:46:16
  • OfStack

rambling

As an Python beginner, not knowing the Python decorators is fine, but as an intermediate Python developer without familiarity with the python decorators, they may not accumulate quantitative to qualitative changes.

I've read a lot of articles about python decorators before, but they're forgettable. The first is not doing too much practice, and the second is not very deep understanding of it.

Hope to learn a lesson!!

Schwartz rs

Decorative pattern

If you know Java, you've heard of the decorator pattern. In object orientation, the decorator pattern refers to dynamically adding 1 additional responsibility to an object. Decorator mode is more flexible than subclassing in terms of adding 1 feature.

In design Pattern Learning-Decorator Pattern, I have extracted the following 1 section of code that USES decorator pattern


public class DecoratorPattern { 
 
  /** 
   * @param args the command line arguments 
*/ 
  public static void main(String[] args) { 
    // TODO code application logic here 
    Basket basket = new Original(); 
    //1 A process of decoration  
    Basket myBasket =new AppleDecorator(new BananaDecorator(new OrangeDecorator(basket)));  
    myBasket.show(); 
  } 
}

Pay attention to the spelling of Basket myBasket =new AppleDecorator(new BananaDecorator(new OrangeDecorator(basket)))

This is how decorators are described in the Python official document, 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.

]

A decorator is a software design pattern that is used to dynamically modify functions, methods, or class functions without subclassing them or modifying the original code.

With before is 1 meaning!!

Python Decorator
The Python decorators are different, according to officials:

[

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.

]

The decorators of Python is not exactly the same as DecoratorPattern. decorator's decorator is a special one: the syntactic implementation allows us more flexibility to change methods, or functions.

Example:


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

Remember this particular syntax, and we'll show you the powerful syntax sugar later


Related articles: