IKH

Introduction

  • Decorator is a function which can take a function as argument and extend its functionality and returns modified function with extended functionality.
  • The main objective of decorator functions is we can extend the functionality of existing functions without modifies that function.

Example

Python
 def wish(name):
   print("Hello",name,"Good Morning")
 wish('Ram')
 wish('Shiv')
 wish('Rajiv')
  • This function can always print same output for any name

Output

PowerShell
Hello Ram Good Morning
Hello Shiv Good Morning
Hello Rajiv Good Morning
  • But we want to modify this function to provide different message if name is ‘Ram’.
  • We can do this without touching wish() function by using decorator.
Python
def decor(func):
  def inner(name):
    if name=="Ram":
      print("Hello Ram Bad Morning")
    else:
      func(name)
  return inner
@decor
def wish(name):
  print("Hello",name,"Good Morning")
wish("Rajiv")
wish("Shiv")
wish("Ram")

Output

PowerShell
Hello Rajiv Good Morning
Hello Shiv Good Morning
Hello Ram Bad Morning
  • In the above program whenever we call wish() function automatically decor function will be executed.

Ungraded Questions

Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!


Name
Email
Phone

Report an error