Home >Backend Development >Python Tutorial >How Do Function Decorators Work, and How Can They Be Chained?
Decorators are functions that modify other functions. They provide a way to enhance or extend the behavior of a function without directly modifying it.
Syntax:
@decorator_function def function_to_decorate(): # Function body
Decorators can be chained, meaning you can apply multiple decorators to the same function. The order in which you chain the decorators matters.
@decorator2 @decorator1 def function_to_decorate(): # Function body
In this example, decorator1 will be applied first, followed by decorator2.
To achieve the desired output, you can create custom decorators:
# Decorator for bolding text def makebold(fn): def wrapper(): return "<b>" + fn() + "</b>" return wrapper # Decorator for italicizing text def makeitalic(fn): def wrapper(): return "<i>" + fn() + "</i>" return wrapper @makebold @makeitalic def say(): return "Hello" print(say()) # Output: "<b><i>Hello</i></b>"
In this example, the @makebold decorator is applied first, followed by @makeitalic. The output is "Hello" enclosed in bold and italic tags.
The above is the detailed content of How Do Function Decorators Work, and How Can They Be Chained?. For more information, please follow other related articles on the PHP Chinese website!