DECORATORS IN PYTHON PROGRAMMING

in OCD5 years ago

Decorators is a concept that belongs to the Functional Programming and you can't find this concept in procedural programming like C/C++ or Object Oriented Programming like Java, Php. Decorators allow you to use another function inside a function and you can use that function to perform different tasks without changing the original function code. Simple understand this concept as "Using Function Inside a Function" Here's a simple program in python which demonstrates the concept of decorators.

def higher_function():
    def lower_function():
        print("How you doing")
    lower_function()
 
higher_function()

You can see the output as:


Screenshot_2.png

Now let's see the working of decorators. We would create a function that subtracts two values like if we passed (3,5) then it will return -2 as output but remember we want to subtract 3 from 5 and returns output as 2 (not negative). Then in this case we use decorators to modify existing function class that subtracts two values.

def subtraction(x,y):
    print(x-y)
    
def sub(func):
    def operation(x,y):
        if x<y:
            x,y=y,x
        return func(x,y)
    return operation

subtraction=sub(subtraction)

subtraction(5,10)

You can see the output as follows:


Screenshot_3.png