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

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

Câu trả lời

The Python nonlocal statement, introduced in Python 3.0, is used to work with variables inside nested functions, where the variable should not belong to the inner function itself but rather to an enclosing scope that is not the global scope. This statement allows the modification of a variable outside of the immediate local scope but within the nearest enclosing scope that is not global.

Key Characteristics of the nonlocal Statement

  1. Scope Modification: The nonlocal statement is used when you need to modify a variable that exists in an outer, but not global, scope. It effectively tells Python to use the variable from the nearest enclosing scope (excluding the global scope) if it exists[1][3][4][5].

  2. Usage Constraints: It cannot be used to declare global variables or to affect variables in the global scope. It only works within nested functions[1][4][5].

  3. Error Handling: If the variable specified after nonlocal is not found in the nearest enclosing scope, Python will raise a SyntaxError. This ensures that the variable must already exist in the outer function before it can be declared nonlocal in the inner function[2][4][5].

  4. Memory Efficiency: By using nonlocal, the memory address of the variable is reused. This can lead to more memory-efficient code because it avoids creating a new local variable ...

middle

middle

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

middle

What does this stuff mean: *args , **kwargs? Why would we use it?

middle

What are virtualenvs?

middle

What are immutable objects in Python?

Bình luận

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

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