Skip to content

Commit e6a1481

Browse files
committed
Python 命名空间和作用域
Python 命名空间和作用域
1 parent e77caab commit e6a1481

File tree

2 files changed

+109
-0
lines changed

2 files changed

+109
-0
lines changed

day-021/python_namespace.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# var1 是全局名称
2+
var1 = 5
3+
4+
def some_func():
5+
# var2 是局部名称
6+
var2 = 6
7+
8+
def some_inner_func():
9+
# var3 是内嵌的局部名称
10+
var3 = 7
11+

day-021/python_scope.py

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import builtins
2+
3+
# 作用域的概述及运用
4+
global_scope = 0 # 全局作用域
5+
6+
# 定义闭包函数中的局部作用域
7+
def outer():
8+
o_count = 1 # 闭包函数外的函数中,相对于函数 inner() 来说 作用域非局部
9+
def inner():
10+
local_scope = 2 # 局部作用域
11+
12+
# 查看模块中引入哪些变量
13+
print('builtins 模块中引入的变量为:%s' %dir(builtins))
14+
15+
16+
# # 其他模块中的变量访问
17+
name1 = 'SuSan'
18+
if('SuSan'.__eq__(name1)):
19+
result = 'I am SuSan,I am from China'
20+
else:
21+
result = 'I am from USA'
22+
23+
print(result)
24+
25+
26+
# 如果将变量定义在函数内部,则外部不能访问
27+
def names():
28+
name2 = 'SuSan'
29+
30+
# if('SuSan'.__eq__(name2)):
31+
result1 = 'I am '+name2 +','+'I am from China'
32+
# else:
33+
result1 = 'I am from USA'
34+
35+
# print(result1)
36+
37+
38+
39+
# 全局变量和局部变量
40+
total = 0 # 这是一个全局变量
41+
# 函数说明
42+
def sum(arg1, arg2):
43+
# 返回2个参数的和."
44+
total = arg1 + arg2 # total在这里是局部变量.
45+
print("函数内是局部变量 : ", total)
46+
return total
47+
48+
# 调用sum函数,传入参数的计算结果显示局部变量
49+
sum(10, 20)
50+
print("函数外是全局变量 : ", total)
51+
52+
53+
# 使用golbal 关键字访问和修改全局变量
54+
num = 1
55+
def fun1():
56+
# 申明访问全局变量
57+
global num # 需要使用 global 关键字声明
58+
# 输出全局变量原始值
59+
print(num)
60+
# 修改全局变量
61+
num = 123
62+
print(num)
63+
# 调用函数
64+
fun1()
65+
# 输出修改后的全局变量值
66+
print(num)
67+
68+
69+
# 使用nonlocal关键字申明变量并修改
70+
# 定义函数
71+
def outer():
72+
# 定义变量
73+
num = 10
74+
# 定义嵌套函数
75+
def inner():
76+
nonlocal num # nonlocal关键字声明,使用函数中变量
77+
# 修改变量值
78+
num = 100
79+
print(num)
80+
inner()
81+
print(num)
82+
outer()
83+
84+
85+
# 特殊情况下
86+
b = 8
87+
def test(b):
88+
b = b * 10
89+
print(b)
90+
test(b)
91+
92+
93+
b = 8
94+
def test():
95+
global b
96+
b = b * 30
97+
print(b)
98+
test()

0 commit comments

Comments
 (0)