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:
- 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()
- Explicit application of the decorator when assigning:
def say_hello():
print("Hello")
say_hello = decorator(say_hello)
say_hello()
- Decorators for classes:
@decorator
class MyClass:
pass
- 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.