Nested Functions
Coddy의 Python 데코레이터 코스 레슨. 12개 중 2번째.
데코레이터를 살펴보기 전에, 파이썬 함수와 관련된 몇 가지 중요한 개념을 이해해야 합니다.
파이썬에서는 함수 내부에 다른 함수를 포함할 수 있으며, 이를 중첩 함수(nested function)라고도 합니다.
예를 들어,
def outer_function():
print("This is the outer function.")
def inner_function():
print("This is the inner function.")
inner_function()
이 예제에서 outer_function은 inner_function이라는 중첩 함수를 포함하고 있습니다.
outer_function이 호출되면, 먼저 "This is the outer function."을 출력한 다음 inner_function을 호출합니다. 그러면 inner_function이 "This is the inner function."을 출력합니다.
inner_function은 outer_function 내부에서만 호출될 수 있다는 점에 유의하세요.
outer_function 외부에서 inner_function을 호출하려고 하면, inner_function이 정의되지 않았다는 NameError가 발생합니다.
챌린지
쉬움이름을 인자로 받아 해당 이름을 포함하는 인사 메시지를 반환하는 greeting_generator라는 함수를 작성하세요.
인사 메시지는 get_greeting이라는 중첩 함수(nested function)에 의해 생성되어야 합니다. 이 중첩 함수는 이름을 인자로 받아 "Hello, [name]!"이라는 문자열을 반환해야 합니다.
함수가 어떻게 작동해야 하는지에 대한 예시는 다음과 같습니다:
>>> greeting = greeting_generator("Alice")
>>> greeting
"Hello, Alice!"
>>> greeting = greeting_generator("Bob")
>>> greeting
"Hello, Bob!"
제약 사항
- 인사 메시지를 생성하기 위해 반드시
get_greeting이라는 중첩 함수를 사용해야 합니다. - 인사 메시지에는
greeting_generator에 전달된 이름이 포함되어야 합니다.
직접 해보기
Python 데코레이터의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러