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.
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()
Run result:
hello python 之前 hello python! hello python 之后
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!