2017年10月7日 星期六

Python - Decorators筆記

將函式當作引數傳給另外一個函式

def new_decorator(func):

    def wrap_func():
        print ("Code would be here, before executing the func")

        func()

        print ("Code here will execute after the func()")

    return wrap_func

def func_needs_decorator():
    print ("This function is in need of a Decorator")

func_needs_decorator()
# Reassign func_needs_decorator
func_needs_decorator = new_decorator(func_needs_decorator)

func_needs_decorator()


等同於以下簡化的方式

def new_decorator(func):

    def wrap_func():
        print ("Code would be here, before executing the func")

        func()

        print ("Code here will execute after the func()")

    return wrap_func

@new_decorator
def func_needs_decorator():
    print "This function is in need of a Decorator"

func_needs_decorator()

沒有留言:

張貼留言