Python 3.4 - Closures


Closures have access to the outer functions arguments and variables. 


def outer_func():
    message = 'hi'
    def inner_func():
        print(message)

    return inner_func

my_func = outer_func() # this creates a function
my_func() # this runs the functon using the out_funcmy_func() # three timesmy_func()

print('---------------------------------')


def outer_func(msg): #this is a bit different because it takes a message now    message = msg # an message is equal to the message variable set
    def inner_func():
        print(message)

    return inner_func

hi_func = outer_func('hi sucka') #these need an argument to workhello_func = outer_func('hello')

hi_func()
hello_func()


print('---------------------------------')


 /Users/mattfassnacht/PycharmProjects/untitled10/venv/bin/python /Users/mattfassnacht/PycharmProjects/untitled10/math.py
hi
hi
hi
---------------------------------
hi sucka
hello

Process finished with exit code 0

https://www.youtube.com/watch?v=swU3c34d2NQ

Comments

Popular posts from this blog

Python 3.4 - Caesar Cipher

UML - Use Case Diagram