Decorative mode and Python adorner

Source: Internet
Author: User
Tags python decorator

Adorners and Decorative modes

The definition of the two is given first:
-adorners: Adorners are a well-known design pattern that is often used for scenes with cut-off requirements, with more classic insert logs, performance tests, transaction processing, and more. Decorators are a great design for solving such problems, and with adorners, we can pull out a lot of the same code that is not relevant to the function itself and continue to reuse it. In summary, the function of an adorner is to add additional functionality to an already existing object.
-Decorative mode: Dynamically extend the functionality of an object without having to change the original class file and use inheritance. It is by creating a wrapper object, that is, decorating to wrap the real object.

Adorners are a technique used by Python's advanced functions to enhance the functionality of an object without modifying the object. This object can be functions, class methods, and generic types. See the "decoration" and its function, for the design pattern is more familiar with the students should think of decorative mode. If you do not think of the adorner or the decorator without a clear conceptual understanding, then come with me to review the decorating pattern. An in-depth understanding of the decorative pattern can be helpful for the adorner's understanding.

Decoration Mode Example

Here we use Java to show a decorative pattern in a simple scene.

Scenario: The program Ape Day and night work can make money, the money saved up can buy a house to buy a car, marry mating, embark on a happy life ...
Here we define an interface that can save money: Cansavemoney, the program Ape class coder.

public  interface  cansavemoney  {  Public  void  save  ( int  money);} Class Coder implements Cansavemoney {private  int  count = 0 ;  @Override  public  void  save  (int  Money) {count + = money; }}/xxx ways to save money Xx/public  void  savemoney  (Cansavemoney person, int  Money) {Person.save (Money)} 

Story continued: After a period of time, the program ape after the goddess, need to cultivate feelings with the goddess. But we just left a savings function without the function of money, no problem, the program apes are smart, we save a negative amount of money is not to be taken to the hemp. In this way the program ape smoothly with the goddess to cultivate good feelings.
The Goddess Management program Ape's income, the goddess saw through the program ape tricks, how to repair the loophole? Goddess is overbearing, goddess think all of the program Ape is hers, program ape pay the wages card, everything through the goddess's hand.

class Godness implements CanSaveMoney {  private Coder coder;  publicGodness(Coder coder) {    this.coder = coder;  }  @Overridepublicvoidsave(int money) {    if0) {      thrownew RuntimeException("滚犊子");    else {      coder.save(money);    }  }}

The above is the use of decorative mode, without altering the original class of the case to enhance a function of the class.

Python decorator

In Python, adorners are a broader application of decorative patterns that can be applied not only to classes, but also to functions, class methods, and Class properties. Flexible use of adorners can greatly improve your python development efficiency.

Simple Adorner Example

Here are some simple examples of adorners that show that you can do some processing before or after a function call.

ImportFunctools# do something before call def log(fun):    @functools. Wraps (Fun)     def wrapper(*args, **kwargs):Print' begin%s () '% fun.__name__)returnFun (*args, **kwargs)returnWrapper# do something before and after call def log2(fun):    @functools. Wraps (Fun)     def wrapper(*args, **kwargs):Print' Begin call%s () '% fun.__name__) F = Fun (*args, **kwargs) print (' End Call ')returnFreturnWrapper# decorator with Param def log_tag(tag):     def log(func):        @functools. Wraps (func)         def wrapper(*args, **kwargs):Print'%s%s () '% (tag, func.__name__))returnFunc (*args, **kwargs)returnWrapperreturnLog#装饰器类, for information that requires several calls to be saved, such as the number of times a function is called class logclass(object):     def __init__(self, f):SELF.F = f Self.count =0        # Copy the properties of the original function         forNinchSet (dir (f))-Set (Dir (self)): SetAttr (self, n, getattr (f, N)) def __call__(self, *args):Self.count + =1Print' called Times:%s '% Self.count)returnSELF.F (*args) def __repr__(self):        returnSelf.f@log_tag ("execute") def print_num(n=0):Print' num is%s '% n)if__name__ = =' __main__ ': forNinchRange1,4): Print_num (n) Print ('%s '% print_num.__name__)
About @functools.wraps()

@functools.wraps()is a very useful adorner in the Functools module, whose function is to copy the properties of the original function into the decorated function. Functions are also objects, so the function's properties are not difficult to understand, for example, you can use pirnt(‘%s‘ % print_num.__name__) to print out the Name property of a function. Here the emphasis is on explaining that the decorated function is not the original function.
The code snippet above finally prints out the Name property of the function, and if we comment out the line in the adorner and @functools.wraps() then print it, the printed result will not be the same print_numm wrapper . Figure out why you understand @functools.wraps() the role.

Why has the decorated function print_num.__name__ changed?

We use @log the form above to use the adorner decorator function, which is called decorator syntax inside Python. The form that does not use the adorner syntax is this

print_num = log(print_num)print_num(n)

So we understand why the function after the decoration is no longer the original function. The above code snippet in the adorner class initializes the code to get the effect of setting the original function property in a similar role @functools.wraps() .

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Decorative mode and Python adorner

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.