What does the Python nonlocal statement do (in Python 3.0 and later)?
What does the Python nonlocal statement do (in Python 3.0 and later)?
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.
nonlocal StatementScope 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.
Usage Constraints: It cannot be used to declare global variables or to affect variables in the global scope. It only works within nested functions.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.