다른 구문들과 마찬가지로 함수도 함수안에 중첩되어 선언될 수 있다.
def parent_function(): def child_function(): print("this is a child function") child_function() parent_function() "this is a child function"
중첩함수(nested function) 혹은 내부 함수는 는 상위 부모 함수 안에서만 호출 가능하다.
부모 함수를 벗어나서 호출될 수 없다.
child_function 함수는 parent_function 안에서 호출이 가능하다.
그렇다면 중첩함수는 왜 사용할까?
중첩함수를 사용하는 이유는 일반적으로 2가지다.
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 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)
1024calculate_power_of_seven = generate_power(7)
calculate_power_of_seven(3)
343
calculate_power_of_seven(5)
16907
Decorator를 구현해보세요.
Decorator는 앞서 배운 closure를 한단계 더 나아가 사용하는 고급 기능입니다.
Decorator는 closure처럼 중첩함수를 리턴하는 함수 이며 다른 함수에 적용해서, 적용된 함수가 실행되기 전에 무조건 실행됩니다. 즉 특정 함수를 실행하기 전에 강제적으로 다른 함수가 먼저 실행된후 실행되도록 하는 강제성을 제공하는 기능입니다.
더 자세한 내용은 아래 링크의 스택오버플로우 질문을 참조하세요:
https://stackoverflow.com/c/wecode/q/64/1
왼쪽 상단의 greeting 함수에 적용될 decorator 함수를 구현하여 greeting 함수에 적용해주세요.
Greeting 함수가 호출 되었을때 decorator 함수에 parametor 값이 greeting 함수 리턴값의 다음에 붙혀져서 리턴되어야 합니다. Decorator 함수의 이름은 name_decorator 여야 합니다.
예를 들어, 다음 처럼 정의 하여 name_decorator decorator에 "정우성"을 parameter로 적용하여 greeting을 호출하면:
@name_decorator("정우성")
def greeting():
return "Hello, "
greeting()
결과값은 다음과 같아야 합니다.
"Hello, 정우성"
My solution
def name_decorator(name): def result_decorator(func): def wrapper(): result = func() + name return result return wrapper return result_decorator @name_decorator("정우성") def greeting(): return "Hello, " greeting()
Model solution
def name_decorator(name): def _decorator(func): def wrapper(): result = func() return result + name return wrapper return _decorator @name_decorator("정우성") def greeting(): return "Hello, "