Nested Function / First-class Function / Closure Function
-
중첩 함수 (Nested function)
함수 내부에 정의된 함수
중첩 함수는 해당 함수가 정의된 함수 내에서 호출 및 변환 가능
중첩 함수는 함수 밖에서는 호출 불가 함수 안에 선언된 변수는 함수 안에서만 사용 가능한 원리와 동일(로컬 변수)
def outer_func():
print("outer_function")
# nested function 정의
def inner_func():
return "inner_function"
print(inner_func())
outer_func()
output
outer_function
inner_function
중첩 함수를 정의된 함수 밖에서 따로 호출할 수 없다.
inner_func()
output
NameError: name 'inner_func' is not defined
First-class function
함수 자체를 변수에 저장 가능
함수의 인자에 다른 함수를 인수로 전달 가능
return 값으로 함수를 전달 가능
파이썬에서는 모든 것이 객체이다. 파이썬 함수도 객체로 되어 있어서 파이썬의 함수들은 First-class function으로 사용 가능하다.
1. 함수 자체를 변수에 저장 가능
함수가 할당된 변수는 동일한 함수처럼 활용이 가능하다.
>>> def add(a,b):
>>> return a + b
>>> test1 = add
>>> test1(2,3)
5
2. 함수의 인자에 다른 함수를 인수로 전달 가능
def list_square(func, digit_list):
result = list()
for digit in digit_list:
result.append(func(digit))
print(result)
def square(a):
return a * a
num_list = [1,2,3]
list_square(square, num_list)
output
[1, 4, 9]
3. 함수의 결과값으로 함수를 반환 가능
이렇게 함수의 결과값으로 중첩 함수를 반환하면 그 함수 밖에서도 중첩 함수를 호출할 수 있다.
def calc_power(n):
def power(digit):
return digit ** n
return power
# closure func들이 들어있는 리스트
func_list = []
for num in range(1,5):
func_list.append(calc_power(num))
for func in func_list:
print(func(2))