Python Basics - Nested Function

Jayson Hwang·2022년 4월 30일
0

15. Nested Function

  • 함수 안에 함수를 선언하는 것이 가능

  • 가독성과 Closure를 위해서 사용

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

15-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!")

15-2. Closure

  • 중첩 함수가 부모 함수의 변수나 정보를 중첩 함수 내에서 사용

  • 부모 함수는 리턴값으로 중첩 함수를 리턴

  • 부모 함수에서 리턴했으므로, 부모 함수의 변수는 직접적인 접근이 불가능하지만,
    부모 함수가 리턴한 중첩 함수를 통해서 사용될 수 있다.

📌 언제 Closure를 사용??

  • 어떤 정보를 기반으로 연산을 실행하고 싶지만,
    정보 접근을 제한하여 노출이 되거나 수정이 되지 못하게 하고 싶을 때 사용
  • 주로 factory 패턴을 구현할때 사용
    즉, 뭔가를 생성해내는 패턴, 주로 함수나 오브젝트 생성에 사용
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

15-3. Decorator

  • 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!"

Reference::

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

profile
"Your goals, Minus your doubts, Equal your reality"

0개의 댓글