一尘不染

对python变量作用域的怀疑

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,我错了吗?


阅读 189

收藏
2021-01-20

共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
2021-01-20