gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:50:21 26 4
gpt4 key购买 nike

<分区>

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 只是打印 fooget_bar 打印 bar 并检查异常get_foobar 使用 try-except 来确保在打印之前设置 foobar。

不知何故,get_foobar 失败了?!

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com