클로저(closure)란?
함수를 둘러썬 환경(지역변수, 코드 등)을 계속 유지하다가,
함수를 호출할 때 다시 꺼내서 사용하하는 함수
class Calc():
def __init__(self):
self.__a = 3
self.__b = 5
def mul_add(self, x):
return self._a * x + self._b
c = Calc()
c.mul_add(1)
>>>> 8
>>> print(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> def foo():
... global x
... x = 1
... print("foo!")
... return x
...
>>>
>>> print(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>>
>>> foo() # foo 함수 안에서 x를 global 변수로 선언함
foo!
1
>>>
>>> print(x) # foo 함수가 실행되자, x라는 글로벌 변수가 생겨서 x를 알게됨
1
>>>
>>> x = 1
>>> print(x)
1
>>>
>>>
>>>
>>> def foo_out():
... x = 11
... y = 22
... print(f"foo_out! x:{x} y:{y}")
... def foo_in():
... nonlocal y
... y = 222
... print(f"foo_in! : x:{x} y:{y}")
... return foo_in
...
>>>
>>> print(x)
1
>>> print(y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>>
>>>
>>>
>>> type(foo_out)
<class 'function'>
>>> type(foo_out())
foo_out! x:11 y:22
<class 'function'>
>>> type(foo_out()())
foo_out! x:11 y:22
foo_in! : x:11 y:222
<class 'NoneType'>
>>>
>>>
>>>
>>> foo_out()
foo_out! x:11 y:22
<function foo_out.<locals>.foo_in at 0x7ffc8c3973a0>
>>> foo_out()()
foo_out! x:11 y:22
foo_in! : x:11 y:222
>>>
>>>
>>>
>>> print(x)
1
>>> print(y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>>