What is a Python decorator and how do you use it?
Share
Sorry, you do not have permission to ask a question.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What is a Python decorator and how do you use it?
A Python decorator is a design pattern that allows you to dynamically extend the behavior of a callable object (functions, methods, or classes) without permanently modifying it. In Python, decorators are defined using the ‘@’ symbol followed by the name of the decorator function or class above the definition of the function, method, or class you want to decorate.
Here is a simple example to demonstrate how you can use a Python decorator:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
In the above example, the `my_decorator` function is used as a decorator to add behavior before and after the `say_hello` function is called. When `say_hello()` is invoked, it actually calls the `wrapper` function defined inside the decorator function `my_decorator`.
This is a basic example, and decorators can be much more complex and versatile in Python based on the use case and requirements.