Advertisement

Decorator in Python

Decorator in Python 


In Python, a decorator is a design pattern that allows you to add new behavior to an existing object, without modifying its code. This is accomplished by "decorating" the object with a function that takes the object as an argument and returns an modified version of the object.


Decorator in Python



Decorators are implemented as a special type of function, called a "decorator function", that takes another function as an argument and returns a modified version of that function. Decorator functions are defined using the @ symbol, which is placed before the function definition.

For example, consider the following code:

def greet(name):

    return
"Hello, " + name
def shout(func):
def wrapper(name):
    return func(name).upper()
    return wrapper greet = shout(greet)
    print(greet("John")) # "HELLO, JOHN"

In this code, the shout function is a decorator function that takes the greet function as an argument and returns a modified version of it. The modified version of the greet function is returned by the wrapper function, which is defined inside the shout function.

The @ symbol can be used to simplify the syntax for applying a decorator to a function. For example, the following code is equivalent to the code above:


def greet(name):
    return "Hello, " + name
def shout(func):
def wrapper(name):
    return func(name).upper()
    return wrapper @shout
def greet(name):
    return "Hello, " + name
    print(greet("John")) # "HELLO, JOHN"

In this case, the @shout symbol is equivalent to writing greet = shout(greet).

Decorators can also be used to add arguments to the wrapper function. For example, consider the following code:
def repeat(num):
def decorator(func):
def wrapper(*args, **kwargs):
    for i in range(num): func(*args, **kwargs)
    return wrapper
    return decorator @repeat(num=3)
def greet(name):
    print("Hello, " + name) greet("John")


In this code, the repeat function is a decorator that takes a single argument, num, which specifies the number of times the decorated function should be called. When the decorated function is called, the wrapper function is called num times, with the same arguments as the original function.

Decorators are a powerful tool in Python, and they can be used to add behavior to existing functions in a clean and elegant way. However, it is important to use them with care, as they can make code more difficult to read and understand if used excessively or in inappropriate situations.

Post a Comment

0 Comments