Sobes.tech
Junior — Middle

What methods can be used to apply a decorator in your code?

sobes.tech AI

Answer from AI

In Python, a decorator can be applied in several ways:

  1. Using @ syntax before defining a function or class:
def decorator(func):
    def wrapper(*args, **kwargs):
        print("Before function call")
        result = func(*args, **kwargs)
        print("After function call")
        return result
    return wrapper

@decorator
def say_hello():
    print("Hello")

say_hello()
  1. Explicit application of the decorator when assigning:
def say_hello():
    print("Hello")

say_hello = decorator(say_hello)
say_hello()
  1. Decorators for classes:
@decorator
class MyClass:
    pass
  1. Using decorators with parameters:
def decorator_with_args(arg):
    def decorator(func):
        def wrapper(*args, **kwargs):
            print(f"Decorator argument: {arg}")
            return func(*args, **kwargs)
        return wrapper
    return decorator

@decorator_with_args("Example")
def say_hello():
    print("Hello")

say_hello()

Thus, a decorator can be applied either via the @ syntax or manually by wrapping the function or class.