# python名稱空間和作用域

``````def f1():
def f2():
print('from f2')
f2()

f2()  # NameError: name 'f2' is not defined
``````

### 一、名稱空間

#### 2 全局名稱空間

``````x = 1

def func():
pass

l = [1, 2]

if 3 > 2:
if 4 > 3:
z = 3
``````

#### 3 局部名稱空間

``````def f1():
def f2():
print('from f2')
f2()

f1()
``````

#### 5 查找順序

``````x = 1
y = 2
len = 100

def func():
y = 3
len = 1000
print(f"y: {y}")
print(f"len: {len}")
# print(a)  # NameError: name 'a' is not defined

func()
``````

``````y: 3
len: 1000
``````
``````x = 1

def func():
print(x)

x = 10
func()
``````

``````10
``````

### 二、作用域

#### 1 全局作用域

``````# 全局作用域
x = 1

def bar():
print(x)

bar()
``````

``````1
``````

#### 2 局部作用域

``````# 局部作用域
def f1():
def f2():
def f3():
print(x)
x = 2
f3()
f2()

f1()
``````

``````2
``````

#### 3 注意點

``````# 作用域注意點
x = 1

def f1():  # 定義階段x=1
print(x)

def f2():
x = 2
f1()

f2()
``````

``````1
``````

### 4 函數對象+作用域應用

``````# 作用域應用
def f1():
def inner():
print('from inner')
return inner

f = f1()  # 把局部定義的函數放在全局之中

def bar():
f()

bar()
``````

``````from inner
``````

### 三、補充知識點

#### 1 global關鍵字

``````x = 1

def f1():
x = 2

def f2():
#         global x  # 修改全局
x = 3
f2()

f1()
print(x)
``````

``````1
``````
``````x = 1

def f1():
x = 2

def f2():
global x  # 修改全局
x = 3
f2()

f1()
print(x)
``````

``````3
``````

#### 2 nonlocal關鍵字

``````x = 1

def f1():
x = 2

def f2():
#         nonlocal x
x = 3

f2()
print(x)

#學習中遇到問題沒人解答？小編創建了一個Python學習交流羣：711312441
f1()
``````

``````2
``````
``````x = 1

def f1():
x = 2

def f2():
nonlocal x
x = 3

f2()
print(x)

f1()
``````

``````3
``````

#### 3 注意點

``````lis = []

def f1():
lis.append(1)

print(f"調用函數前: {lis}")
f1()
print(f"調用函數後: {lis}")
``````

``````調用函數前: []

``````