define a decorator in python ?
In Python, a decorator is a design pattern that allows you to extend or modify the functionality of a class or function without directly modifying the code of the original class or function.
Decorators are implemented as functions that take another function as an argument and return a modified version of that function. They are typically used to add a particular behavior to an existing function or class, or to extend the function or class in some way.
Here is a simple example of how you might define a decorator in Python:
def my_decorator(func):
def wrapper(*args, **kwargs):
# Do something before the original function is called
result = func(*args, **kwargs)
# Do something after the original function is called
return result
return wrapper
@my_decorator
def my_function(arg1, arg2):
# Original function code goes here
pass
In this example, the my_decorator function is a decorator that takes a function (func) as an argument and returns a modified version of that function (the wrapper function). The @my_decorator syntax above the my_function definition is used to apply the decorator to the my_function function.
Recommended by LinkedIn
Here is an example of how you might use a decorator to extend the functionality of a function:
def logger(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with arguments {args} and keyword arguments {kwargs}")
result = func(*args, **kwargs)
print(f"Result: {result}")
return result
return wrapper
@logger
def add(x, y):
return x + y
@logger
def multiply(x, y):
return x * y
add(1, 2)
# Output: Calling add with arguments (1, 2) and keyword arguments {}
# Result: 3
multiply(3, 4)
# Output: Calling multiply with arguments (3, 4) and keyword arguments {}
# Result: 12
:
In this example, the logger decorator is applied to the add and multiply functions. When these functions are called, the decorator logs the arguments and result of the function call before and after the original function is called.
Decorators can be useful for adding functionality to existing functions or classes without modifying their code, and can help to keep your code clean and organised.
Do you have any other questions about decorators in Python?