IKH

Practice Question

Question

Give an example of decorator?

Python
def decor(func):
  def inner(name):
    if name=="Amit":
      print("Hello Amit Bad Morning")
    else:
      func(name)
  return inner

def wish(name):
  print("Hello",name,"Good Morning")

decorfunction=decor(wish)
wish("Ajay")
wish("Amit")
decorfunction("Manish")
decorfunction("Amit")

Output

PowerShell
Hello Ajay Good Morning
Hello Amit Good Morning
Hello Manish Good Morning
Hello Amit Bad Morning

Question

How to call same function with decorator and without decorator?

Python
def smart_division(func):
  def inner(a,b):
    print("We are dividing",a,"with",b)
    if b==0:
      print("OOPS...cannot divide")
      return
    else:
      return func(a,b)
  return inner

#@smart_division
def division(a,b):
    return a/b

print(division(20,2))
print(division(20,0))
  • Without decorator i.e. decorator not applied.
PowerShell
10.0 
ZeroDivisionError: division by zero
  • With decorator i.e. line-11 uncommented.

Output

PowerShell
We are dividing 20 with 2
10.0
We are dividing 20 with 0
OOPS...cannot divide
None

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