Decorators in Python

Previous
Next

Decorators:

  • Allow the programmer to wrap another function in order to extend the behavior of wrapper function, without permanently modifying it.
  • In Decorators, functions are takes as arguments(input values) to another function.
def fun1():
    print("In fun1")
    return

def fun2(x):
    print("In fun2")
    x()
    return

fun1()
fun2(fun1)

Decorator program:

def my_decorator(func):
    def wrapper():
        print("basic wrapped func")
        func()
        print("Something happend")
        return

    return wrapper

def say_whee():
    print("whee!")
    return

say_whee = my_decorator(say_whee)
say_whee()
Previous
Next

Add Comment

Courses Enquiry Form