<클로저(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
### 클로저 함수 호출하기
- outer만 호출되었기 때문에 inner는 메모리를 받아서 정의만 되고 실행되지 않았다.
- closure_exe는 0x000001DA19EF1800 값을 받은 inner함수 그 자체가 된 것이다.
- closure_exe는 inner_function 자체를 리턴받은 함수를 의미함
closure_exe = outer_function(10)
print(closure_exe)
#1 : x = 10
#4 -------
<function outer_function.<locals>.inner_function at 0x000001DA19DE9120>
### 내부 함수 호출하기
- 내부 함수는 실행되고 끝나면 소멸된다
result1 = closure_exe(5)
print(result1)
#2 : y = 5
#3 : s = 15
15
<클로저를 이용해서 프로그램 만들기>
- 클로저를 이용해서 누적합 계산하기
- 사용함수명 : outer_function2(), inner_function2(num)
- 사용변수 : total(누적된 값을 저장할 변수)
- total은 바깥 함수에 둬야 함.
- total은 지역변수가 아니므로 안쪽 함수에서 total을 가져오려면 nonlocal 선언을 해줘야 함.
- nonlocal : 클로저 구조에서는 상위 변수를 내부 함수에서 사용 못한다. 따라서 nonlocal을 지정해서 정의하면 외부 영역의 변수 사용 가능해진다. (바깥에 있는 total을 쓴다는 의미)
def outer_function2() :
total = 0
print(f"#1 : total = {total}")
def inner_function2(num) :
nonlocal total
print(f"#2 : total = {total} / num = {num}")
total += num
print(f"#3 : total = {total} / num = {num}")
return total
print("#4 -------")
return inner_function2
### 클로저 함수 호출하기
res_fnc = outer_function2()
print(res_fnc)
#1 : total = 0
#4 -------
<function outer_function2.<locals>.inner_function2 at 0x000001DA1A479580>
### 내부 함수 호출
rs_total = res_fnc(5)
print(rs_total)
#2 : total = 0 / num = 5
#3 : total = 5 / num = 5
5
rs_total = res_fnc(8)
print(rs_total)
#2 : total = 5 / num = 8
#3 : total = 13 / num = 8
13
<조건부 클로저 함수 프로그래밍>
- condition의 값이 true이면 true_case함수 정의, falsedlaus false_case함수 정의
def outer_function3(condition) :
def true_case() :
return "true_case 함수가 호출되었습니다."
def false_case() :
return "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 0x00000231AA761A80>
<function outer_function3.<locals>.false_case at 0x00000231AA762160>
### 내부 함수 호출하기
rs_msg = rs_function()
print(rs_msg)
false_case 함수가 호출되었습니다.
'Digital Boot > Python' 카테고리의 다른 글
[Python] 파이썬 매개변수 (1) | 2023.11.14 |
---|---|
[Python] 파이썬 도서 관리 프로그램 만들기 실습 2 (0) | 2023.11.14 |
[Python] 파이썬 유니코드 프로그램 (1) | 2023.11.14 |
[Python] 파이썬 도서 관리 프로그램 만들기 실습 (1) | 2023.11.13 |
[Python] 파이썬 문자열 메소드, 정규식 (2) | 2023.11.09 |