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

Why aren't Python nested ...

Câu trả lời

Nested functions in Python are functions defined within other functions. They are not necessarily closures, although they can lead to the creation of closures. A closure, in contrast, is a specific type of nested function that captures and retains access to variables from its enclosing scope, even after the outer function has finished executing.

The distinction between nested functions and closures lies in the concept of "free variables." A free variable is a variable that is not bound in the local scope but is accessed by a nested function. When a nested function captures these free variables, it becomes a closure. This means that the nested function retains access to those variables even when the function in which it was defined has completed execution.

Nested functions become closures when they satisfy the following conditions:

  1. The nested function must reference at least one variable that is defined in an enclosing function's scope.
  2. The nested function is returned from the enclosing function, allowing it to be called after the enclosing function has executed.

If a nested function does not capture any free variables from its enclosing scope, or if it does not outlive the execution of its outer function, it is not considered a closure. It is simply a nested function.

For example, consider the following code snippet:

def outer_function(text):
    def inner_func...
senior

senior

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

middle

What does the Python nonlocal statement do (in Python 3.0 and later)?

junior

Does Python have a switch-case statement?

senior

What is an alternative to GIL?

Bình luận

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

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