Non-local Scope
The non-local scopes are outer local scopes. This means that the non-local scope is placed between global scope and function local scope:
Let's look at the code example:
123456789101112131415161718def first_outer(): first = "first_outer() local scope" def second_outer(): second = "second_outer() local scope" def inner(): third = "inner() local scope" print("Inner non-local:", first) print("Inner non-local:", second) print("Inner local:", third) inner() second_outer() first_outer()
The first_outer()
local and second_outer()
local scope are non-local scopes for the inner()
function.
Access to change non-local objects
You can change the non-local variable or another object using the nonlocal
keyword (similar to the global
keyword):
12345678910111213def outer(): some_variable = 255 def inner(): nonlocal some_variable print(some_variable) some_variable += 233 print(some_variable) inner() outer()
Note
Why pay attention to non-local scope?
The non-local scope is used for the closure. That's why non-local scope is also named enclosing scope. The closure will be described in the next section.
Danke für Ihr Feedback!
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen
Fragen Sie mich Fragen zu diesem Thema
Zusammenfassen Sie dieses Kapitel
Zeige reale Beispiele
Awesome!
Completion rate improved to 6.67
Non-local Scope
Swipe um das Menü anzuzeigen
The non-local scopes are outer local scopes. This means that the non-local scope is placed between global scope and function local scope:
Let's look at the code example:
123456789101112131415161718def first_outer(): first = "first_outer() local scope" def second_outer(): second = "second_outer() local scope" def inner(): third = "inner() local scope" print("Inner non-local:", first) print("Inner non-local:", second) print("Inner local:", third) inner() second_outer() first_outer()
The first_outer()
local and second_outer()
local scope are non-local scopes for the inner()
function.
Access to change non-local objects
You can change the non-local variable or another object using the nonlocal
keyword (similar to the global
keyword):
12345678910111213def outer(): some_variable = 255 def inner(): nonlocal some_variable print(some_variable) some_variable += 233 print(some_variable) inner() outer()
Note
Why pay attention to non-local scope?
The non-local scope is used for the closure. That's why non-local scope is also named enclosing scope. The closure will be described in the next section.
Danke für Ihr Feedback!