Can you explain Closures (...
Can you explain Closures (...
In Python, a closure is a nested function that captures and retains access to variables from its enclosing scope, even after the outer function has finished executing. This allows the closure to remember the values of those variables for future calls.
A closure involves at least two functions: an outer function and an inner function. The inner function is defined within the body of the outer function and is not accessible outside its defining scope, except when the outer function returns the inner function.
The key feature of closures is their ability to capture non-local variables from the enclosing function's environment. These are variables that are neither in the local nor the global scope. They are defined in the outer function and used in the inner function.
Here's a simple example to illustrate how closures work in Python:
def outer_function(msg):
message = msg # A non-local variable
def inner_function():
print(message) # Accessing the non-local variable
return inner_function # Return the inner function
my_closure = outer_function("Hello, world!")
my_closure()
In this example, outer_function
creates a local variable message
and defines a nested function inner_function
that prints message
. The outer_function
then returns inner_function
. Even after outer_function
has finished execution, my_closure
can still access the message
variable when called. This is because inner_function
has closed over (or captured) message
.
Data Encapsulation: Closures can encapsulate data in a function, hiding it from the global scope. This helps in maintaining state between function calls without using global variables.
*...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào