** 데코레이터는 하나의 함수를 취해서 또 다른 함수를 반환하는 함수다. **
def document_it(func):
def new_function(*args, **kwargs):
print('Running function:', func.__name__)
print('Positional arguments:', args)
print('Keyword arguments:', kwargs)
print('args', args)
result = func(*args, **kwargs)
print('Result_doc', result)
return result
return new_function
def add_ints(a, b):
return a + b
add_ints(3,5)
8
cooler_add_ints= document_it(add_ints)
cooler_add_ints(3,5)
Running function: add_ints Positional arguments: (3, 5) Keyword arguments: {} args (3, 5) Result_doc 8 8
수동으로 데코레이터를 적용함
@document_it def sub_ints(a, b): return a-b
sub_ints(3,5)
Running function: sub_ints Positional arguments: (3, 5) Keyword arguments: {} args (3, 5) Result_doc -2 -2 ** 자동으로 `@데코레이터_이름 을 추가하여 사용 가능하다 **
def square_it(func): def new_function(*args, **kwargs): print('square_args:', args) result = func(*args, **kwargs) print('square:', result) return result * result return new_function
@document_it @square_it def add_ints(a, b): return a + b
add_ints(3, 5)
Running function: new_function Positional arguments: (3, 5) Keyword arguments: {} args (3, 5) square_args: (3, 5) square: 8 Result_doc 64 64
@square_it @document_it def add_ints(a, b): return a + b
add_ints(3,5)
square_args: (3, 5) Running function: add_ints Positional arguments: (3, 5) Keyword arguments: {} args (3, 5) Result_doc 8 square: 8 64
Comments