Sobes.tech
Junior — Middle

How are decorators created and applied to functions or methods in Python?

sobes.tech AI

Answer from AI

In Python, decorators are functions that take another function and return a new function with extended behavior.

Decorators are usually created like this:

def decorator(func):
    def wrapper(*args, **kwargs):
        # code before calling the function
        result = func(*args, **kwargs)
        # code after calling the function
        return result
    return wrapper

Applying a decorator to a function:

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

say_hello("Alice")

When calling say_hello, actually wrapper is called, which can add additional logic before and after calling the original function.

Decorators are often used for logging, access control, measuring execution time, and other aspects.

For class methods, decorators work similarly, for example:

class MyClass:
    @decorator
    def method(self):
        pass

There are also built-in decorators, such as @staticmethod, @classmethod.