Artificial Intelligence
Please fill the required field.

explain decorators in python with examples.

Decorators in python are special functions that can modify the behavior of other functions or classes without changing their source code. Decorators are generally used to add additional functionality, such as logging, caching, or error handling, to existing functions. Example 1: Simple decorator ``` # defining a decorator def print_msg(func): # inner function that will add additional functionality def inner(): print("Before executing function") # calling the original function func() print("After executing function") return inner # using the decorator @print_msg def hello(): print("Hello!") # calling the decorated function hello() ``` Output: ``` Before executing function Hello! After executing function ``` In this example, the `print_msg` decorator adds the functionality of printing a message before and after the execution of the `hello` function. Example 2: Decorator with arguments ``` # defining a decorator def multiply_by_n(n): # inner function that accepts a function def decorator(func): # inner function that will add additional functionality def inner(x): # multiplying the return value of func by n return n * func(x) return inner return decorator # using the decorator @multiply_by_n(2) def square(x): return x * x # calling the decorated function print(square(5)) print(square(10)) Output: 50 200 ``` In this example, the `multiply_by_n` decorator takes an argument `n` and the inner function `inner` multiplies the returned value of the function it decorates by `n`. Example 3: Class decorators ``` # defining a decorator def lowercase(func): # inner function that will modify the behavior of the function def inner(*args, **kwargs): # calling the function and storing its return value value = func(*args, **kwargs) # converting returned value to lowercase return value.lower() return inner # class decorated with the lowercase decorator @lowercase class Person: def __init__(self, name): = name def greet(self): return f"Hello, my name is {}." # creating an instance of the class person = Person("John") # calling the function decorated with the decorator print(person.greet()) Output: hello, my name is john. ``` In this example, the `lowercase` decorator modifies the behavior of the `greet` method in the `Person` class by converting the returned string to lowercase. This is helpful when we want to ensure consistent output from a class method.