Skip to main content
 首页 » 编程设计

python之使用 try/except 时 Python 中的奇怪变量范围

2024年11月01日8duanxz

<分区>

foo = 'asdf' 
bar = 'asdf' 
foobar = 'asdf' 
 
def test(): 
  def get_foo(): 
    print 'foo = ' + foo 
 
  def get_bar(): 
    try: 
      print 'bar = ' + bar 
    except Exception as e: 
      print 'nobody set bar :(' 
 
  def get_foobar(): 
    try: 
      foobar 
    except Exception as e: 
      print e 
      foobar = "nobody set foobar :(" 
    print foobar 
 
  print 'trying to get foo' 
  get_foo() 
 
  print '\ntrying to get bar' 
  get_bar() 
 
  print '\ntrying to get foobar' 
  get_foobar() 
 
test() 

当我运行它时,我得到了这个:

trying to get foo 
foo = asdf 
 
trying to get bar 
bar = asdf 
 
trying to get foobar 
local variable 'foobar' referenced before assignment 
nobody set foobar :( 

我设置了三个变量:foo、bar、foobar。然后,我使用三个嵌套函数将它们打印出来:get_foo、get_bar 和 get_foobar。

get_foo 只是打印 foo get_bar 打印 bar 并检查异常 get_foobar 使用 try-except 来确保在打印之前设置 foobar。

不知何故,get_foobar 失败了?!