Python Decorators

In Python, a decorator is a special type of function that can modify the behavior of another function without changing its source code. Decorators are often used to add extra functionality to functions, like logging or timing, without cluttering up the function with additional code.

Here’s an example of a simple decorator function in Python:

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, and returns a new function wrapper. wrapper is the decorated function that will replace func.

The @my_decorator syntax is used to apply the decorator to the say_hello() function. This is equivalent to calling say_hello = my_decorator(say_hello).

When say_hello() is called, it will actually call the wrapper() function instead. wrapper() will print “Before the function is called.”, call func() (which is the original say_hello() function), and then print “After the function is called.”

The output of this example would be:

Before the function is called.
Hello!
After the function is called.

Decorators can be very powerful, and are often used in conjunction with other Python features like classes and context managers.

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial