How to add multiple decorators to a function in Python

anonymity
Release: 2020-09-17 16:11:26
Original
4207 people have browsed it

How to add multiple decorators to a function in Python: You can use @ before the function name to add decorators one by one, such as [@decorator1 @decorator2]. Decorators, like objects, can be assigned to a variable or defined in other functions.

How to add multiple decorators to a function in Python

Function in Python is an object, which can be assigned and defined. Multiple decorators need to be added one by one using @ before the function name. The execution order is from From top to bottom, the specific operation process needs to be carried out in the function decorator.

First of all, we know that functions are objects, so objects can be assigned to a variable or defined in other functions.

So the same goes for decorators. In this example, two decorators are customized, and then two decorators are added to the test() function, and the running result is normal.

#!/usr/bin/env python  
#coding:utf-8  
def decorator1(func):  
    def wrapper():  
        print 'hello python 之前'  
        func()  
    return wrapper  
  
def decorator2(func):  
    def wrapper():  
        func()  
        print 'hello python 之后'  
    return wrapper  
 
@decorator1  
@decorator2  
def test():  
    print 'hello python!'  
  
test()
Copy after login

Run result:

hello python 之前
hello python!
hello python 之后
Copy after login

The above is the detailed content of How to add multiple decorators to a function in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template