*Memos:
Without a global or nonlocal statement, the closest non-local variable or a global variable can be referred to in order as shown below:
<Read>:
""" It's from the viewpoint of `third()` """
num = 2 # <- ✖
class Cls1:
num = 3 # <- ✖
class Cls2:
num = 4 # <- ✖
def first(self):
num = 5 # <- ✖
def second():
num = 6 # <- 〇
def third():
print(num) # 6
third()
second()
Cls1().Cls2().first()
""" It's from the viewpoint of `third()` """
num = 2 # <- ✖
class Cls1:
num = 3 # <- ✖
class Cls2:
num = 4 # <- ✖
def first(self):
num = 5 # <- 〇
def second():
# num = 6 # <- Commented
def third():
print(num) # 5
third()
second()
Cls1().Cls2().first()
""" It's from the viewpoint of `third()` """
num = 2 # <- 〇
class Cls1:
num = 3 # <- ✖
class Cls2:
num = 4 # <- ✖
def first(self):
# num = 5 # <- Commented
def second():
# num = 6 # <- Commented
def third():
print(num) # 2
third()
second()
Cls1().Cls2().first()
""" It's from the viewpoint of `third()` """
# num = 2 # <- Commented
class Cls1:
num = 3 # <- ✖
class Cls2:
num = 4 # <- ✖
def first(self):
# num = 5 # <- Commented
def second():
# num = 6 # <- Commented
def third():
print(num) # NameError: name 'num' is not defined.
third() # Did you mean: 'sum'?
second()
Cls1().Cls2().first()
<Change>:
""" It's from the viewpoint of `third()` """
num = 2 # <- ✖
class Cls1:
num = 3 # <- ✖
class Cls2:
num = 4 # <- ✖
def first(self):
num = 5 # <- ✖
def second():
num = 6 # <- ✖
def third():
num += 10 # UnboundLocalError: cannot access
print(num) # local variable 'num' where it is
third() # not associated with a value
second()
Cls1().Cls2().first()
Using both a global and nonlocal statement in the same function gets error as shown below:
""" It's from the viewpoint of `third()` """
num = 2 # <- ✖
class Cls1:
num = 3 # <- ✖
class Cls2:
num = 4 # <- ✖
def first(self):
num = 5 # <- ✖
def second():
num = 6 # <- ✖
def third():
global num # SyntaxError: name 'num'
nonlocal num # is nonlocal and global
print(num)
third()
second()
Cls1().Cls2().first()
""" It's from the viewpoint of `third()` """
num = 2 # <- ✖
class Cls1:
num = 3 # <- ✖
class Cls2:
num = 4 # <- ✖
def first(self):
num = 5 # <- ✖
def second():
num = 6 # <- ✖
def third():
nonlocal num # SyntaxError: name 'num'
global num # is nonlocal and global
print(num)
third()
second()
Cls1().Cls2().first()