python
python 알고리즘 기초2 (클로저함수)
멈머이
2023. 11. 14. 23:05
728x90
1. 클로저를 이용해서 누적합 계산하기
# - 사용 함수 명 : 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)>
#1 과 #4가 가장 큰 껍데기 역할을 한다.
### 내부 함수 호출1
rs_total = res_fnc(5)
print(rs_total)
결과 : #2 : total = 0 / num = 5
#3 : total = 5 / num = 5
5
가장 큰 껍데기 내부의 함수의 내부에 #2 와 #3이 다음으로 작동한다.
### 내부 함수 호출2
rs_total = res_fnc(10)
print(rs_total)
결과 : #2 : total = 5 / num = 10
#3 : total = 15 / num = 10
15
첫번째로 호출했던 내부함수의 10과 두번째로 호출한 내부함수5가 더해지면서 결과가 15가 된다.
2. 조건부 클로저 함수 프로그래밍
def outer_function3(condition):
def true_case():
return "true_case 함수가 호출되었습니다"
def false_case():
return "false_case 함수가 호출되었습니다"
### conditoin의 값이 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 0x000001B1AC70D4E0>-----> 함수의 메모리 주소
<function outer_function3.<locals>.false_case at 0x000001B1AC7E3380> -----> 함수의 메모리 주소
rs_msg = rs_function()
print(rs_msg)
결과 : false_case 함수가 호출되었습니다.
false가 나온 이유는 True가 실행된 이후에 False가 실행되었기 때문.
위에서부터 읽어 내려오는 파이썬의 특징.
728x90