InterviewSolution
| 1. |
What are Closures in Python? |
|
Answer» Python allows a function to be defined inside another function. Such functions are called nested functions. In such case, a certain variable is located in the order of local, outer, global and lastly built-in namespace order. The inner function can access variable declared in nonlocal scope. >>> DEF outer(): DATA=10 def inner(): PRINT (data) inner() >>> outer() 10Whereas the inner function is able to access the outer scope, inner function is able to use variables in the outer scope through closures. Closures maintain references to objects from the earlier scope. A closure is a nested function object that REMEMBERS values in ENCLOSING scopes even if they are not present in memory. Following criteria must be met to create a closure in Python:
Following code is an example of closure. >>> def outer(): data=10 def inner(): print (data) return inner >>> closure=outer() >>> closure() 10 |
|