Home >Backend Development >Python Tutorial >How Do Function Decorators Work, and How Can They Be Chained?

How Do Function Decorators Work, and How Can They Be Chained?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-27 03:13:11364browse

How Do Function Decorators Work, and How Can They Be Chained?

Function Decorators and Chaining

What are Function Decorators?

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

Chaining Decorators

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.

Example

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!

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