SW/메모
[python] python decorator
luminovus
2023. 2. 4. 23:20
반응형
python의 decorator는 함수 객체를 입력받아 새로운 함수 함수 객체(decorated function)을 만들어준다.
num1 = 3
num2 = 8
def call_test(func):
def wrapper():
print(f"called func : {func.__name__} !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print(f"before call func. num1 --> {num1}, num2 --> {num2}")
func()
print(f"after call func. num1 --> {num1}, num2 --> {num2}")
return wrapper
def first():
# global로 num을 변경할 수 있다.
global num1
num1 = 5
print(f"first. num1 --> {num1}, num2 --> {num2}")
def second():
num1 = 11
print(f"second. num1 --> {num1}, num2 --> {num2}")
# annotation 으로 호출
@call_test
def third():
print(f"third. num1 --> {num1}, num2 --> {num2}")
print(f"before {globals()}")
# 호출방식1
call_test_first = call_test(first)
call_test_first()
call_test_second = call_test(second)
call_test_second()
# 호출방식2
third()
#num1이 변경되었음
print(f"after {globals()}")
before {'__name__': '__main__' ... 'num1': 3, 'num2': 8, 'call_test': <function call_test at 0x1025c4790>, 'first': <function first at 0x1025c4dc0>, 'second': <function second at 0x1025d8940>, 'third': <function call_test.<locals>.wrapper at 0x1025d8a60>}
called func : first !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
before call func. num1 --> 3, num2 --> 8
first. num1 --> 5, num2 --> 8
after call func. num1 --> 5, num2 --> 8
called func : second !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
before call func. num1 --> 5, num2 --> 8
second. num1 --> 11, num2 --> 8
after call func. num1 --> 5, num2 --> 8
called func : third !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
before call func. num1 --> 5, num2 --> 8
third. num1 --> 5, num2 --> 8
after call func. num1 --> 5, num2 --> 8
after {'__name__': '__main__' ... 'num1': 5, 'num2': 8, 'call_test': <function call_test at 0x1025c4790>, 'first': <function first at 0x1025c4dc0>, 'second': <function second at 0x1025d8940>, 'third': <function call_test.<locals>.wrapper at 0x1025d8a60>, 'call_test_first': <function call_test.<locals>.wrapper at 0x1025d8af0>, 'call_test_second': <function call_test.<locals>.wrapper at 0x1025d8b80>}
반응형