# child_function은 parent_function 안에서만 호출이 가능함.
def parents_function():
def child_function():
print("child function 이라고,,")
child_function()
parents_function()
def print_all_elements(list_of_things): # 부모 함수
def print_each_element(things): # 중첩 함수
for thing in things:
print(thing)
if len(list_of_things) > 0:
print_each_element(list_of_things)
else:
print("없어요")
print_all_elements([1,2,3,4,4])
closure
라고 한다. 그리고 부모함수는 중첩함수를 retuen 해준다. 즉 부모 함수에서 리턴했으므로 부모 함수의 변수는 직접적인 접근이 불가능 하지만 부모 함수가 리턴한 중첩 함수를 통해서 사용될 수 있다.factory 패턴
을 구현할 때 사용(뭔가를 생성해내는 패턴)예시를 들어 설명하면
# 특정 숫자의 승을 구하는 함수를 구현한다면?
def calculate_poser_of_two(power):
return 2 ** power
print(calculate_poser_of_two(7))
print(calculate_poser_of_two(5))
하지만 위의 함수는 2의 승밖에 구할 수 없다. 만약에 특정 숫자의 승을 구하는 함수가 필요 하지만 2가 아니라 원하는 수의 승을 구하는 함수를 어떻게 구현할 수 있을까? 이때 closure
함수를 사용하면 된다.
# 특정 숫자의 승을 구하는 함수를 구현한다면?
def generate_power(base_number):
def nth_power(power):
return base_number ** power
return nth_power
num = generate_power(5)
print(num(2))
#25
➡️ 부모함수의 변수인 base_number
이 중첩함수에 격리되어 사용된다(= closure). 그리고 중첩함수가 부모함수의 return 값으로 리턴됨을 확인할 수 있다.