본문 바로가기
Python Basic

closure 사용법

by fiasco 2022. 11. 23.

https://dojang.io/mod/page/view.php?id=2364 

 

파이썬 코딩 도장: 33.1 변수의 사용 범위 알아보기

Unit 33. 클로저 사용하기 이번에는 변수의 사용 범위와 함수를 클로저 형태로 만드는 방법을 알아보겠습니다. 참고로 클로저는 개념이 다소 어려울 수 있으므로 변수의 사용 범위부터 알아본 뒤

dojang.io

 

함수안의 함수

def print_hello():
    hello = 'Hello, world!'

    def print_message():
        print(hello)

    print_message()

print_hello()


클로저

클로저를 사용하면 프로그램의 흐름을 변수에 저장할 수 있습니다. 
즉, 클로저는 지역 변수와 코드를 묶어서 사용하고 싶을 때 활용합니다. 
또한, 클로저에 속한 지역 변수는 바깥에서 직접 접근할 수 없으므로 데이터를 숨기고 싶을 때 활용합니다.

- 함수, 변수를 바깥함수로 감싸라
- 함수의 반환값을 내부 함수명으로 지정하라

#closure1 : 

def print_hello():
    hello = 'Hello, world!'

    def print_message():
        print(hello)

    return print_message

a=print_hello()
a()


# closure2 : 

def print_hello(x):

    def print_message():
        print(x)

    return print_message

a=print_hello('hello')
a()


# closure3 :

def print_hello():

    def print_message(x):
        print(x)

    return print_message

a=print_hello()
a('hello')


#closure4 : 람다를 이용한 closure

def calc():
    a = 3
    b = 5
    return lambda x: a * x + b    # 람다 표현식을 반환
 
c = calc()
print(c(1), c(2), c(3), c(4), c(5))


#closure4 : nonlocal 사용

def calc():
    a = 3
    b = 5
    total = 0
    def mul_add(x):
        nonlocal total
        total = total + a * x + b
        print(total)
    return mul_add
 
c = calc()
c(1)
c(2)
c(3)

 

https://fiasco-at-python.tistory.com/47

'Python Basic' 카테고리의 다른 글

Exception  (0) 2022.11.23
decorator 사용법  (0) 2022.11.23
Programming productivity tools  (0) 2022.11.08
Debugging  (0) 2022.11.08
Emulating Python's interactive interpreter  (0) 2022.11.08