本文介绍了关于python变量作用域的疑惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
Python 范围规则的简短描述
我写了两个简单的函数:
I wrote two simple functions:
# 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,我错了吗?
In comparison, test1()
assigns value after print var
, then raise an Exception: UnboundLocalError: local variable 'var' referenced before assignment
, I think the moment I call inner print var
, var has a value of 2, am I wrong?
推荐答案
是的,您在这里不正确.函数定义引入了一个新的作用域.
Yes, you're incorrect here. Function definition introduces a new scope.
# 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
这篇关于关于python变量作用域的疑惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!