<클로저 (Closure)>
- 함수 안에 함수를 만들어서 사용하는 방식
- 함수 안에 있는 함수는 바깥쪽 함수에서 참조해서 사용하는 방식으로 접근한다.
- 함수 안에 함수는 사용이 끝나면 메모리에서 해제되기 떄문에 유용하게 사용하면 좋다.
### 클로저 함수 생성하기
def outer_function(x) :
print(f"#1 : x = {x}")
### 내부 함수 정의 : 실제 실행되는 함수
def inner_function(y) :
print(f"#2 : y = {y}")
s = x+ y
print(f"#3 : s = {s}")
return s
print("#4 ----------")
return inner_function
### 클로저 함수 호출하기
closure_exe = outer_function(10)
print(closure_exe)
# - closure_exe 는 inner_Function 자체를 리턴받은 함수를 의미한다.
#1 : x = 10
#4 ----------
<function outer_function.<locals>.inner_function at 0x000002050F45A200>
#2 : y = 5
#3 : s = 15
15
# 안쪽 함수에서 큰 데이터를 처리할때 처리후 소멸시키기 (메모리 효율적)
# 따로 쓴다면 메모리에 계속 차있게 된다.
# 밖같쪽에서는 안쪽 함수를 쓸수없고 쓰려면 글로벌하거나 클래스로 묶어서 self로 꺼내쓴다.
# 클래스 안에서 쓴다면 self 밖이라면 글로벌
### 클로저를 이용해서 누적합 계산하기
# - 사용함수명 : outer_function2(), inner_function2(num)
# - 사용변수 : total(누적된 값을 저장할 변수)
def outer_function2():
total = 0
print(f"#1 : total = {total}")
def inner_function2(num):
### nonlocal : 클로저 구조에서는 상위 변수를 내부 함수에서 사용못함
# : 따라서, nonlocal을 지정해서 정의하면 외부 영역의 변수 사용가능
nonlocal total
print(f"#2 : total = {total} / num = {num}")
total += num
print(f"#3 : total = {total} / num = {num}")
return total
print(f"#4-----------------")
return inner_function2
### 상위 함수 호출
res_fnc = outer_function2()
res_fnc
#1 : total = 0
#4-----------------
<function __main__.outer_function2.<locals>.inner_function2(num)>
### 내부함수 호출
rs_total = res_fnc(5)
print(rs_total)
#2 : total = 0 / num = 5
#3 : total = 5 / num = 5
5
### 내부함수 호출
rs_total = res_fnc(10)
print(rs_total)
#2 : total = 5 / num = 10
#3 : total = 15 / num = 10
15
<조건부 클로저 함수 프로그래밍>
## 데이터 양이 많아 프로그램이 버벅거릴때 사용하면 좋음
def outer_function3(condition) :
def true_case() :
return "true_case 함수가 호출되었습니다."
def false_case() :
return "false_case 함수가 호출되었습니다."
### condition의 값이 True 이면 true_case함수 정의
### False이면 false_case함수 정의
rs = true_case if condition else false_case
return rs
### 상위 함수 호출하기
rs_function = outer_function3(True)
print(rs_function)
rs_function = outer_function3(False)
print(rs_function)
<function outer_function3.<locals>.true_case at 0x000002050F498A40>
<function outer_function3.<locals>.false_case at 0x000002050F499300>
rs_msg = rs_function()
print(rs_msg)