Thursday, 27 April 2017

Closures in python

what is the Closure function:

defining the normal function  by satisfying following rules is known as a closure function.

  • must be define a nested function(function inside function).
  • nested function must refer to a value defined in the Enclosing function.
  • the enclosing function must return the nested function.

def print_message(msg): ---> enclosing function

    def printer( ):  ----> nested function

        print(msg)

    return printer

message=print_message("hello siva")

message( )

hello siva.

After removing the enclosing function  namespace/object still we can call nested function.

def print_message(msg):

    def printer( ):

        print(msg)

    return printer

message=print_message("hello siva")

message( )

del print_message

message( )

hello siva

hello siva

Example:

def make_multiplier_of(n):

    def multiplier(x):

        return x*n

    return multiplier

times3=make_multiplier_of(3)

times5=make_multiplier_of(5)

print(times3(9))

print(times5(3))

print(times5(times3(2)))


27

15

30

Example:

x=10
def f1( ):
    y=20
    print(x)
    print(y)
def f2( ):
    z=30
    print(x)
    print(z)
f1( )
f2( )

  • Whenever f1( ) is executed over, y value is erased/removed from the memory location, here y is local variable, this is the one problem in functions.
  • to solve the above problem, we are going to use the concept called  global variables, global variable value is modified some other time, this is the problem.
  • to overcome above problem,we are going to use the concept called closure function.
Closures can be used in the following  situations:
  • closures can avoid the use of global variable values and provides some from data hiding.
  • instead of defining the class with one method define the closure function.

No comments:

Post a Comment