Closures and Decorators in Python✌
Nested Functions:
When a function is defined in another function ,it is called nested function.This is also called inner function.
To define an inner function in Python, we simply create a function inside another function using the Python's def
keyword. Here is an example:
Example:
def function1(): # outer function print ("Hello from outer function") def function2(): # inner function print ("Hello from inner function") function2() function1()
>>Hello from outer function
Hello from inner function
Concept of nonlocal variable:
When a variable is defined as nonlocal it is neither global nor local.The variable declared nonlocal refreshes to a new variable to be used with the initialization there after.
Example:
x = 'jack'
def myouter():
x = 'sam'
def myinner():
nonlocal x
x = 'tom'
print('hello',x)
myinner()
print('outer x is',x)
myouter()
print('global x is',x)
>>hello tom
outer x is tom
global x is jack
Closures:
The closure method is somewhat like a nested function, the only difference is we are returning the function without the parentheses instead of calling it. Here we are referring the function to another variable so it can be called even if we deleted the original function from the memory (only after referring).
Generally, closure is used for Encapsulation. Let's try the above nested function in the closure method.
Example:
def myfunc1(x):
def myfunc2():
print('hello'+' ' + x)
return myfunc2
>>greeting = myfunc1('tom')
greeting()
hello tom
Decorators:
Here you can pass a function as an argument of another function, and the syntax is by giving the “@” operator on top of the function.
Example:
def myfunc1(func):
def myfunc2():
print('hello world')
func()
return myfunc2
def printname():
print('I am python')
>>result = myfunc1(printname)
result()
hello world
I am python
Example:
def myfunc1(func):
def myfunc2():
print('hello world')
func()
return myfunc2
@myfunc1
def printname():
print('I am python')
>>printname()
hello world
I am python
Comments
Post a Comment