-
[Python] - Closure개발/Python 2022. 7. 28. 20:59
Closure
1. Nested functions
A function that is defined inside another function is known as a nested function.
- Nested functions are able to access variables of the enclosing scope.
- In Python, these non-local variables can be accessed only within their scope and not outside their scope. But Closure can be access non-local variables
#nested function example def nested_func(text): temp = text def test2(): print( 'temp : {}'.format(temp)) return test2() # free_variable is non-local variable nested_func('test') > temp : test
2. Closure
A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory.
- It is a record that stores a function together with an environment: a mapping associating each free variable of the function
- A closure—unlike a plain function—allows the function to access those captured variables through the closure’s copies of their values or references, even when the function is invoked outside their scope.
- below example The function test has its scope only inside the closure function. But with the use of closures, we can easily extend its scope to invoke a function outside its scope.
- Closures provide some form of data hiding.
- A closure can also be a highly efficient way to preserve state across a series of function calls.
# free variable = str def closure(text): text = text def test(): print( 'free variable : {}'.format(text)) return test a = closure('closure_test') print(a) > <function closure.<locals>.test at 0x0000017E492D8700> a() > free variable : closure_test
# free variable = function def logger(func): def log_func(*args): print(func(*args)) return log_func def risk_up(x,y): return x+y def risk_down(x,y): return x-y add_logger = logger(risk_up) add_logger(3,3) # > 6 sub_logger = logger(risk_down) sub_logger(6,2) # > 4
'개발 > Python' 카테고리의 다른 글
[Python] - 동작원리( Build , hybrid ) (0) 2022.09.18 [Python] - Decorator (0) 2022.09.02 [Python] - First class functions (0) 2022.07.28 [Python] - Generator (0) 2022.07.28 [Python] - Call by Object reference & Call by sharing (0) 2022.07.28