Here is an example of a Python decorator:

def my_decorator(func):
    def wrapper():
        print('Before the function is called.')
        func()
        print('After the function is called.')
    return wrapper

@my_decorator
def say_hello():
    print('Hello!')

say_hello()

In this example, 'my_decorator' is a function that takes another function, 'func', as an argument. It creates and returns a new function, 'wrapper', which adds some extra behavior to the original function.

The '@my_decorator' syntax is shorthand for calling 'my_decorator' with 'say_hello' as an argument and replacing 'say_hello' with the returned 'wrapper' function.

When 'say_hello()' is called, it will first execute the code in 'wrapper' before executing the code in 'say_hello'. This allows us to add extra functionality to our functions without modifying the original code.

Python Decorator Example: Enhancing Functions with Decorators

原文地址: https://www.cveoy.top/t/topic/mMJE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录