Decorators

What Are Decorators?

  • In Python, a decorator is a special type of function used to modify the behavior of another function.

Define a Decorator Function:

  • A decorator takes a function as input, adds some functionality to it, and returns the modified function.

    python
    def mydecorator(fn):
        def inner_function():
            print('Hello! ', end='')
            fn()
        return inner_function
    

Applying a Decorator to a Function:

  • Decorators are applied using the "@" symbol just above the function to be decorated.

    python
    @mydecorator
    def greet():
        print('Good morning!')
    
    greet()
    
    • Output:

       
      Hello! Good morning!
      

Decorator with Arguments:

  • Decorators can accept arguments and pass them to the decorated function.

    python
    def mydecorator(fn):
        def inner_function(*args, **kwargs):
            print('Hello! ', end='')
            fn(*args, **kwargs)
        return inner_function
    
    @mydecorator
    def greet(name):
        print(name)
    
    greet('Ram!')
    
    • Output:

       
      Hello! Ram!
      

Uses of Decorators:

  • Decorators can be used for various purposes such as logging, timing, authentication, etc.

Types of Decorators:

  1. Function Decorators: Most common, applied to functions.
  2. Class Decorators: Modify the behavior of a class.
  3. Method Decorators: Applied to methods within a class.
  4. Property Decorators: Applied to class properties.

Exercises:

  1. Create a Simple Decorator:
    • Define a decorator that prints "Start" before and "End" after calling the decorated function.

      python
      def mydecorator(fn):
          def inner_function():
              print("Start")
              fn()
              print("End")
          return inner_function
      
      @mydecorator
      def greet():
          print('Hello!')
      
      greet()
      
    • Output:

       
      Start
      Hello!
      End
      
  2. Decorator with Arguments:
    • Create a decorator that prints a custom message before calling the decorated function.

      python
      def mydecorator(fn):
          def inner_function(message):
              print(message)
              fn()
          return inner_function
      
      @mydecorator
      def greet():
          print('Hello!')
      
      greet('Welcome!')
      
    • Output:

       
      Welcome!
      Hello!
      

Summary:

  • Decorators are powerful tools in Python for modifying function behavior without changing the function's code. They are used for adding features, logging, timing, and more. Practice creating and using decorators to master this concept!