#!/usr/bin/python
# Filename: func_local.py
def func(x):
print 'x is', x
x = 2
print 'Changed local x to', x
x = 50
func(x)
print 'x is still', x
(源文件:code/func_local.py)
輸出
$ python func_local.py
x is 50
Changed local x to 2
x is still 50
它如何工作
在函數(shù)中,我們第一次使用 x 的 值 的時(shí)候,Python 使用函數(shù)聲明的形參的值。
接下來,我們把值 2 賦給 x。x 是函數(shù)的局部變量。所以,當(dāng)我們?cè)诤瘮?shù)內(nèi)改變 x 的值的時(shí)候,在主塊中定義的 x 不受影響。
在最后一個(gè) print 語句中,我們證明了主塊中的 x 的值確實(shí)沒有受到影響。