Python的命名空间和变量作用域
2021-05-05 22:30
标签:global glob var dict ict 全局 就是 pac ted Python的命名空间和变量作用域 标签:global glob var dict ict 全局 就是 pac ted 原文地址:https://www.cnblogs.com/MartinLwx/p/13191464.html命名空间(Namespaces)
dict
来理解(事实上也是这么实现的)
print()
,type()
之类变量作用域(Variable Scope)
举个例子
global
,nonlocal
修饰的情况下a = 1
def outer_function():
a = 2
def nested_function():
a = 3
print(f"I am in Nested_function {a}")
nested_function()
print(f"I am in outer_function {a}")
outer_function()
print(f"I am not in outer_function {a}")
# I am in Nested_function 3
# I am in outer_function 2
# I am not in outer_function 1
global
修改的情况下,可以看出我们修改了全局变量的a
,a = 1
def outer_function():
a = 2
def nested_function():
global a
a = 3
print(f"I am in Nested_function {a}")
nested_function()
print(f"I am in outer_function {a}")
outer_function()
print(f"I am not in outer_function {a}")
# I am in Nested_function 3
# I am in outer_function 2
# I am not in outer_function 3
nonlocal
修改的情况下,可以看出我们修改的是父函数中的a
,这也符合我们之前所说的查找顺序,这里是从嵌套函数的Local Namespaces–>父函数的Local Namespacesa = 1
def outer_function():
a = 2
def nested_function():
nonlocal a
a = 3
print(f"I am in Nested_function {a}")
nested_function()
print(f"I am in outer_function {a}")
outer_function()
print(f"I am not in outer_function {a}")
# I am in Nested_function 3
# I am in outer_function 3
# I am not in outer_function 1
下一篇:opencv-python使用