怀疑python变量范围

Doubts about python variable scope

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Short Description of Python Scoping Rules

我写了两个简单的函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# coding: utf-8
def test():
    var = 1
    def print_var():
        print var
    print_var()
    print var

test()
# 1
# 1
def test1():
    var = 2
    def print_var():
        print var
        var = 3
    print_var()
    print var

test1()
# raise Exception

相比之下,test1()print var后赋值,然后提出一个例外:UnboundLocalError: local variable 'var' referenced before assignment,我认为当我调用内部print var时,var值为2,我错了吗?


是的,你这里不正确。函数定义引入了一个新的范围。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# coding: utf-8
def test():
    var = 1
    def print_var():
        print var    <--- var is not in local scope, the var from outer scope gets used
    print_var()
    print var

test()
# 1
# 1
def test1():
    var = 2
    def print_var():
        print var     <---- var is in local scope, but not defined yet, ouch
        var = 3
    print_var()
    print var

test1()
# raise Exception