TIL[49]. Python_ Nested Function

jake.log·2020년 8월 23일
0

Python

목록 보기
31/39

31.Nested Function

다른 구문들과 마찬가지로 함수도 함수안에 중첩되어 선언될 수 있다.

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 안에서 호출이 가능하다.

Why use nested function?

그렇다면 중첩함수는 왜 사용할까?
중첩함수를 사용하는 이유는 일반적으로 2가지다.

  1. 가독성
    예시)
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!")
  1. Closure
  • 중첩 함수가 부모 함수의 변수나 정보를 중첩 함수 내에서 사용한다.
  • 부모 함수는 리턴값으로 중첩 함수를 리턴한다.
  • 부모 함수에서 리턴 했으므로 부모 함수의 변수는 직접적인 접근이 불가능 하지만 부모 함수가 리턴한 중첩 함수를 통해서 사용될 수 있다.

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)
1024

calculate_power_of_seven = generate_power(7)
calculate_power_of_seven(3)
343
calculate_power_of_seven(5)
16907

Assignment

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, "
profile
꾸준히!

0개의 댓글