Python 3.4 - Decorators

 You can not only run messages through other functions but you can run other functions through functions. And you can run multiple, other functions through functions.


def outer_func(msg):
    message = msg

    def inner_func():
        print(message)

    return inner_func #this is important, notcie how the inner function isn't returning anything yet
hi_func = outer_func('hi') # now the variable hi_func is loaded with the return value of the inner function# and has th message stored
hi_func() # this now prints or runs the functions with the () included

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



def decor_func(orig_function): # so now this is going to runa function instead of a message.
    def wrapper_function(): # this will return the orig_function within the decor_func        return orig_function()

    return wrapper_function

def display(): # this is the function begin returned within the other functions    print('display function is working')

decor_display = decor_func(display) # this sets the variable function
decor_display() #this runs the new function
print('-------------------------------')



def decor_func(orig_function):
    def wrapper_function():
        print('wrapper executed before {}'.format(orig_function.__name__))
        return orig_function()

    return wrapper_function

def display():
    print('display function is working')

decor_display = decor_func(display)

decor_display()


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


def decor_func(orig_function):
    def wrapper_function():
        print('wrapper executed before {}'.format(orig_function.__name__))
        return orig_function()

    return wrapper_function

def display():
    print('display function is working')

display = decor_func(display)

display()

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

/Users/mattfassnacht/PycharmProjects/untitled10/venv/bin/python /Users/mattfassnacht/PycharmProjects/untitled10/math.py
hi
-------------------------------
display function is working
-------------------------------
wrapper executed before display
display function is working
-------------------------------
wrapper executed before display
display function is working
-------------------------------

Process finished with exit code 0


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

Comments

Popular posts from this blog

Python 3.4 - Caesar Cipher

UML - Use Case Diagram