Câu hỏi phỏng vấn Python
Câu hỏi

Can you explain Closures (...

Câu trả lời

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.

Understanding Closures in Python

Nested Functions

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.

Capturing Non-Local Variables

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.

Example of a Closure

Here's a simple example to illustrate how closures work in Python:

python Copy
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.

Practical Uses of Closures

  1. 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.

  2. *...

senior

senior

Gợi ý câu hỏi phỏng vấn

middle

What are Decorators in Python?

middle

Explain the UnboundLocalError exception and how to avoid it?

expert

Is there a simple, elegant way to define singletons?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào