티스토리 뷰

Python

함수 데코레이터

techbard 2016. 4. 29. 11:30

# Functions within Functions


def hello(name = 'Jose'):

def greet():

return '\t This indise the greet() function'


def welcome():

return '\t This indise the welcome() function'


if name == 'Jose':

return greet

else:

return welcome


x = hello()


print(x())


# 결과

This inside the greet() function


# Functions as Arguments


def hello():

return "Hi! Jose!"


def other(func):

print("Other code goes here!")

print(func())


other(hello)


# 결과

Other code goes here!

Hi! Jose!


# Wrap Function


def new_decorator(func):


def wrap_func():

print("Code here, before executing the func")


func()


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


return wrap_func


def func_needs_decorator():

print("This function needs a decorator!")



func_needs_decorator = new_decorator(func_needs_decorator)


func_needs_decorator()


# 결과

Code here, before executing the func

This function needs a decorator!

Code here will execute after the func()


# 장식자 표기법을 사용해서 수동으로 데코레이터 할당을 대신함


def new_decorator(func):


def wrap_func():

print("Code 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 needs a decorator!")


func_needs_decorator()


# 결과

Code here, before executing the func

This function needs a decorator!

Code here will execute after the func()


댓글
댓글쓰기 폼
공지사항
Total
411,812
Today
1
Yesterday
14
«   2020/01   »
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31  
글 보관함