2

可能重复:
Python 范围规则的简短描述

我写了两个简单的函数:

# 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,然后引发 Exception: UnboundLocalError: local variable 'var' referenced before assignment,我认为在我调用 inner 的那一刻print var, var 的值为 2,我错了吗?

4

1 回答 1

1

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

# 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
于 2012-09-12T06:43:09.077 回答