🐍 When you need to use a function and add more code to it while retaining original function, you can use decorator.
A decorator is nothing but a function to which another function is passed, and both are run.
First we will look at Closure in Python. It is calling of a function inside another function from outside. Example of a Closure:
Now we need not save returned function to call them. It can will be directly called and functions addfunc and subfunc will be passed as we used decorator
A decorator is nothing but a function to which another function is passed, and both are run.
First we will look at Closure in Python. It is calling of a function inside another function from outside. Example of a Closure:
def one(func):def two(*args):print(f"You are running function {two.__name__} and have passed arguments as follows: {args}")print(f"Result of the two numbers {args[0]} and {args[1]} is {func(*args)}")return twodef addfunc(x,y):print("Addition")return x+ydef subfunc(x,y):print("Subtraction")return x-y
addouter = one(addfunc)subouter = one(subfunc)addouter(4,3)subouter(4,3)
Output
You are running function two and have passed arguments as follows: (4, 3)
Addition
Result of the two numbers 4 and 3 is 7
You are running function two and have passed arguments as follows: (4, 3)
Subtraction
Result of the two numbers 4 and 3 is 1
- Created function "one" with another function inside it named "two"
- Function "one" returns function "two"
- Function "two" calls the function passed to function "one"
- We created two more functions named "addfunc" and "subfunc". These functions adds two numbers passed to it and subtracts two numbers passed to it respectively.
- We passed these functions to function "one"
Now let's try the same thing using decorator
def one(func):def two(*args):print(f"You are running function {two.__name__} and have passed arguments as follows: {args}")print(f"Result of the two numbers {args[0]} and {args[1]} is {func(*args)}")return two@onedef addfunc(x,y):print("Addition")return x+y@onedef subfunc(x,y):print("Subtraction")return x-yaddfunc(4, 3)subfunc(4, 3)
Output
You are running function two and have passed arguments as follows: (4, 3)
Addition
Result of the two numbers 4 and 3 is 7
You are running function two and have passed arguments as follows: (4, 3)
Subtraction
Result of the two numbers 4 and 3 is 1
Comments
Post a Comment