Sobes.tech
Junior — Middle

Can you explain the concept of decorators in Python and their usage?

sobes.tech AI

Answer from AI

Decorators in Python are functions that take another function and return a new function with extended behavior, without modifying the original function's source code. They are often used to add additional logic, such as logging, access control, caching, etc.

Example of usage:

def decorator(func):
    def wrapper(*args, **kwargs):
        print("Before calling the function")
        result = func(*args, **kwargs)
        print("After calling the function")
        return result
    return wrapper

@decorator
def say_hello(name):
    print(f"Hello, {name}!")

say_hello("World")

Output:

Before calling the function
Hello, World!
After calling the function

Thus, decorators allow modifying the behavior of functions or methods in a convenient and readable way.

Can you explain the concept of decorators in Python… - sobes.tech