一、全局變量
全局變量是在函數(shù)外部定義的變量,可以在整個(gè)程序的任何位置訪問。在函數(shù)內(nèi)部,可以使用global關(guān)鍵字聲明全局變量,在函數(shù)內(nèi)部修改全局變量的值。
global_variable = "This is a global variable."
def access_global_variable():
print(global_variable)
def modify_global_variable():
global global_variable
global_variable = "Modified global variable."
access_global_variable() # 輸出 "This is a global variable."
modify_global_variable()
access_global_variable() # 輸出 "Modified global variable."
二、局部變量
局部變量是在函數(shù)內(nèi)部定義的變量,其只在函數(shù)內(nèi)部可用,如果函數(shù)外部想要訪問,需要將其作為函數(shù)返回值返回。在函數(shù)內(nèi)部想要修改局部變量的值,需要使用global關(guān)鍵字聲明。
def access_local_variable():
local_variable = "This is a local variable."
print(local_variable)
def modify_local_variable():
local_variable = "This is a local variable."
print("Before modification: ", local_variable)
local_variable = "Modified local variable."
print("After modification: ", local_variable)
access_local_variable() # 輸出 "This is a local variable."
modify_local_variable()
# 輸出
# Before modification: This is a local variable.
# After modification: Modified local variable.
三、參數(shù)
函數(shù)的參數(shù)是在函數(shù)定義時(shí)指定的,可以在函數(shù)內(nèi)部使用,如果沒有使用global聲明,其僅在函數(shù)內(nèi)部可用。
def access_parameter(parameter):
print(parameter)
def modify_parameter(parameter):
print("Before modification: ", parameter)
parameter = "Modified parameter."
print("After modification: ", parameter)
access_parameter("This is a parameter.")
# 輸出 "This is a parameter."
modify_parameter("This is a parameter.")
# 輸出
# Before modification: This is a parameter.
# After modification: Modified parameter.
四、嵌套函數(shù)中的變量名稱
如果在一個(gè)函數(shù)內(nèi)部再定義一個(gè)函數(shù),那么嵌套函數(shù)可以訪問其外部函數(shù)中定義的變量。在嵌套函數(shù)內(nèi)部,如果修改外部函數(shù)的變量,需要使用nonlocal關(guān)鍵字聲明。
def outer_function():
outer_variable = "This is an outer variable."
def inner_function():
print("Inner function: ", outer_variable)
inner_function()
outer_function() # 輸出 "Inner function: This is an outer variable."
def modify_outer_variable():
outer_variable = "This is an outer variable."
def inner_function():
nonlocal outer_variable
outer_variable = "Modified outer variable."
print("Inner function: ", outer_variable)
inner_function()
print("Outer function: ", outer_variable)
modify_outer_variable()
# 輸出
# Inner function: Modified outer variable.
# Outer function: Modified outer variable.
五、總結(jié)
Python函數(shù)在其定義和調(diào)用期間可以訪問全局變量、局部變量、參數(shù)以及嵌套函數(shù)中的變量名稱。在訪問和修改變量的時(shí)候,需要注意使用global、nonlocal關(guān)鍵字進(jìn)行聲明。