IKH

Decorator Chaining

  • We can define multiple decorators for the same function and all these decorators will form decorator chaining.

Syntax

Python
@decor1
@decor
def fun():
  # Business Requirment
  • For fun() function we are applying 2 decorator functions. First inner decorator will work then outer decorator.

Example

Python
def decor1(func):
  print('decor1 executed')
  def inner():
    x=func()
    return x*x
  return inner

def decor(func):
  print('decor executed')
  def inner():
    x=func()
    return 2*x
  return inner

@decor1
@decor
def num():
    return 10
print(num())

Output

PowerShell
decor executed
decor1 executed
400

Example

Python
def decor(func):
  def inner(name):
    print("First Decor(decor) Function Execution")
    func(name)
  return inner

def decor1(func):
  def inner(name):
    print("Second Decor(decor1) Execution")
    func(name)
  return inner

@decor1
@decor
def wish(name):
    print("Hello",name,"Good Morning")
wish("Naveen")

Output

PowerShell
Second Decor(decor1) Execution
First Decor(decor) Function Execution
Hello Naveen Good Morning

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