def parent_function():
def child_function():
print("this is a child function")
child_function()
parent_function()
>"this is a child function"
중첩함수는 상위 부모 함수 안에서만 호출 가능하다. 부모 함수를 벗어나서 호출 x.
위의 코드에서 child_function는 parent_function안에서만 호출 가능하다.
factory
뭔가를 생성해내는 패턴. 주로 함수나 오브젝트를 생성해내는데 사용된다.
factory에서 뭔가를 생성해 내기 위해서는 설정값이 필요할것이다.
특정 숫자의 승을 구하는 함수 구현
2의 승을 구하는 함수구현
def calculate_power_of_two(power):
return 2 ** power
calculate_power_of_two(7)
>128
이 함수는 2의 승밖에 구할 수 없다.
따라서 closure를 사용하여 2가아닌 설정되는 수의 승을 구하는 함수를 구현할 수 있다.
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_seven = generate_power(7)
calculate_power_of_seven(3)
> 343
Decorator를 구현해보세요.
Decorator는 앞서 배운 closure를 한단계 더 나아가 사용하는 고급 기능입니다.
Decorator는 closure처럼 중첩함수를 리턴하는 함수 이며 다른 함수에 적용해서, 적용된 함수가 실행되기 전에 무조건 실행됩니다. 즉 특정 함수를 실행하기 전에 강제적으로 다른 함수가 먼저 실행된후 실행되도록 하는 강제성을 제공하는 기능입니다.
더 자세한 내용은 아래 링크의 노션 자료를 참조하세요:
https://www.notion.so/wecode/Decorator-8e6eb41d0f95474c94ed0136bcbfc2b1
왼쪽 상단의 greeting 함수에 적용될 decorator 함수를 구현하여 greeting 함수에 적용해주세요.
Greeting 함수가 호출 되었을때 decorator 함수에 parametor 값이 greeting 함수 리턴값의 다음에 붙혀져서 리턴되어야 합니다. Decorator 함수의 이름은 welcome_decorator 여야 합니다.
예를 들어, 다음 처럼 정의 하여 welcome_decorator decorator를 적용하여 greeting을 호출하면:
@welcome_decorator
def greeting():
return "Hello, "
greeting()
결과값은 다음과 같아야 합니다.
"Hello, welcome to WECODE!"
나의 답:
def welcome_decorator(func): #호출함수를 매개변수로 받기
def greeting2():
return func() +"welcome to WECODE!" #리턴값에 호출함수 + 문자열
return greeting2
@welcome_decorator
def greeting():
return "Hello, "
greeting()
https://www.notion.so/Decorator-8e6eb41d0f95474c94ed0136bcbfc2b1
데코레이터는 장식하다, 꾸미다라는 뜻의 decorate에 er(or)을 붙인 말인데 장식하는 도구 정도로 설명할 수 있다.
@로 시작하는 것들이 데코레이터이다.
데코레이터는 함수를 수정하지 않은 상태에서 추가 기능을 구현할 때 사용한다.