在Python中,local
關鍵字用于在函數內部聲明一個局部變量。局部變量只在函數內部有效,當函數執行完畢后,局部變量會被銷毀。這意味著局部變量不會影響到函數外部的代碼或全局變量。
下面是一個簡單的例子來說明局部變量如何影響函數調用:
# 全局變量
global_var = "I am a global variable"
def my_function():
# 局部變量
local_var = "I am a local variable"
# 函數內部訪問全局變量
print("Inside the function, accessing global variable:", global_var)
# 函數內部訪問局部變量
print("Inside the function, accessing local variable:", local_var)
# 調用函數
my_function()
# 訪問全局變量
print("Outside the function, accessing global variable:", global_var)
# 試圖訪問局部變量(這將導致錯誤)
print("Outside the function, trying to access local variable:", local_var)
輸出:
Inside the function, accessing global variable: I am a global variable
Inside the function, accessing local variable: I am a local variable
Outside the function, accessing global variable: I am a global variable
Outside the function, trying to access local variable: NameError: name 'local_var' is not defined
從輸出中可以看到,局部變量local_var
僅在my_function
內部有效,而在函數外部無法訪問。這有助于保護數據封裝和避免意外修改全局變量。