A decorator is a design pattern that allows a user to add new functionality to an existing object or function without modifying its structure. In Python, a decorator is a callable that takes a callable as input and returns another callable. Here is an example of how to create a decorator for a function in Python:
main.py321 chars17 lines
In the example above, we define a decorator my_decorator
that takes a function func
as input and returns a new function wrapper
. The wrapper
function adds some additional behavior before and after calling the original function func
.
We then decorate the function say_hello
by adding @my_decorator
before its definition. This is equivalent to calling say_hello = my_decorator(say_hello)
.
When we call say_hello()
, the Python interpreter automatically calls my_decorator(say_hello)()
which returns the wrapper
function. We then call the wrapper
function which prints "Before the function is called.", calls the original say_hello
function, and prints "After the function is called."
gistlibby LogSnag