클로져(Closure)에 대한 말들은 많다. 최근 핫하다고는 하지만 전산의 태동기부터 존재하던 문법이다. 1급 객체(First class Object)를 지원하는 언어는 자연스럽게 지원하지만 개념 자체를 이해 못하는 경우가 많다.

파이선과 연계해서 클로져(Closure)를 설명하는 좋은 설명이 있어서 소개하고자 한다.

Objects are data with methods attached, closures are functions with data attached.

객체는 메서드가 달라붙어 있는 데이타라면, 클로져는 데이타가 달라붙은 함수이다.

예제는

def make_counter():
  i = 0
  def counter(): # counter() is a closure
    nonlocal i
    i += 1
    return i
  return counter

c1 = make_counter()
c2 = make_counter()

print (c1(), c1(), c2(), c2())
# -> 1 2 1 2

위에서 보면 counter 라는 함수가 i 라는 데이타를 포함하고 있는 클로져(closure)다.

http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python

+ Recent posts