Home  >  Article  >  Backend Development  >  Examples of decorator cascades in Python

Examples of decorator cascades in Python

黄舟
黄舟Original
2017-10-03 05:45:421182browse

A decorator is essentially a Python function, which allows other functions to add additional functions without making any code changes. The following article mainly introduces you to the use of decorator cascades in Python. , friends in need can refer to it, let’s learn together.

Preface

I have been learning python recently, and I have learned why to use decorators and what decorators are, but you may You will ask, if you can add another layer of decorators in front of the decorators, what will happen? Just like a building, layers are stacked one on top of the other. In fact, it is possible. Now let's learn this stacking technology, which is similar to class inheritance and can be continuously inherited. Not much to say below, let’s take a look at the detailed introduction.

The code is as follows:


##

#python 3.6 
def star(func): 
  def inner(*args, **kwargs): 
    print("*" * 30) 
    func(*args, **kwargs) 
    print("*" * 30) 
  return inner 
 
def percent(func): 
  def inner(*args, **kwargs): 
    print("%" * 30) 
    func(*args, **kwargs) 
    print("%" * 30) 
  return inner 
 
@star 
@percent 
def printer(msg): 
  print(msg) 
printer("Hello")

The result output is as follows:



******************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Hello
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
******************************

In this example, the asterisk is output first, that is, the first-layer decorator star is called first, then the second-layer decorator percent is called, and finally the function printer is called .

Summarize

The above is the detailed content of Examples of decorator cascades in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn