约蟒可变范围的疑虑[复制](Doubts about python variable scope [

2019-06-28 06:30发布

可能重复:
简要说明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 ,然后抛出一个异常: UnboundLocalError: local variable 'var' referenced before assignment ,我想我打电话内的瞬间print var ,变种具有为2的值,我错了?

Answer 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


文章来源: Doubts about python variable scope [duplicate]
标签: python scope