함수 안에 함수를 선언하는 것이 가능
가독성과 Closure를 위해서 사용
def parent_function():
def child_function():
print("this is a child function")
child_function()
parent_function()
> "this is a child function"
child_function
함수는 parent_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("There is nothing!")
중첩 함수가 부모 함수의 변수나 정보를 중첩 함수 내에서 사용
부모 함수는 리턴값으로 중첩 함수를 리턴
부모 함수에서 리턴했으므로, 부모 함수의 변수는 직접적인 접근이 불가능하지만,
부모 함수가 리턴한 중첩 함수를 통해서 사용될 수 있다.
📌 언제 Closure를 사용??
def calculate_power(number, power):
return number ** power
calculate_power(2, 7)
> 128
def calculate_power_of_two(power):
return 2 ** power
calculate_power_of_two(7)
> 128
calculate_power_of_two(10)
> 1024
def generate_power(base_number):
def nth_power(power):
return base_number ** power
return nth_power
calculate_power_of_two = generate_power(2)
calculate_power_of_two(7)
> 128
calculate_power_of_two(10)
> 1024
calculate_power_of_seven = generate_power(7)
calculate_power_of_seven(3)
> 343
calculate_power_of_seven(5)
> 16907
Decorator는 closure처럼 중첩함수를 return 하는 함수 이며,
다른 함수
에 적용해서, 적용된 함수
가 실행되기 전에 무조건 실행
특정 함수를 실행하기 전에 강제적으로 다른 함수가 먼저 실행된후 실행되도록 하는 강제성을 제공하는 기능
def welcome_decorator(func):
# 아래에 코드를 작성해 주세요.
def wrapper():
return func() + "welcome to WECODE!"
return wrapper
@welcome_decorator
def greeting():
# 아래에 코드를 작성해 주세요.
return "Hello, "
>> # "Hello, welcome to WECODE!"
https://www.youtube.com/watch?v=tNSOaA1z6Uo :: Closure Animation
https://www.youtube.com/watch?v=3XRSULw-HlE :: ProgrammingKnowledge
https://blog.hexabrain.net/347 :: 설명자료
https://wecode.notion.site/Decorator-8e6eb41d0f95474c94ed0136bcbfc2b1 :: Decorator