以下代码在Python 2.5和3.0中按预期工作:
a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
Run Code Online (Sandbox Code Playgroud)
但是,当我取消注释行(B)时,我得到了UnboundLocalError: 'c' not assigned一行(A).的值a和b被正确地打印.这让我感到困惑,原因有两个:
为什么在行(A)处抛出运行时错误,因为后面的行(B)语句?
为什么变量a和b打印符合预期,同时c引发错误?
我能想到的唯一解释是,赋值创建了一个局部变量,即使在创建局部变量之前,它也优先于"全局"变量.当然,变量在存在之前"窃取"范围是没有意义的.cc+=1c
有人可以解释一下这种行为吗?
我正在尝试在Python 2.6中实现一个闭包,我需要访问一个非局部变量,但似乎这个关键字在python 2.x中不可用.如何在这些版本的python中访问闭包中的非局部变量?
我正在解析文件,我想检查每一行与几个复杂的正则表达式.像这样的东西
if re.match(regex1, line): do stuff
elif re.match(regex2, line): do other stuff
elif re.match(regex3, line): do still more stuff
...
Run Code Online (Sandbox Code Playgroud)
当然,为了做这些事情,我需要匹配对象.我只能想到三种可能性,每种可能性都有所不足.
if re.match(regex1, line):
m = re.match(regex1, line)
do stuff
elif re.match(regex2, line):
m = re.match(regex2, line)
do other stuff
...
Run Code Online (Sandbox Code Playgroud)
这需要进行两次复杂的匹配(这些是长文件和长正则表达式:/)
m = re.match(regex1, line)
if m: do stuff
else:
m = re.match(regex2, line)
if m: do other stuff
else:
...
Run Code Online (Sandbox Code Playgroud)
随着我进一步缩进,这变得非常糟糕.
while True:
m = re.match(regex1, line)
if m:
do stuff
break
m = re.match(regex2, line)
if m: …Run Code Online (Sandbox Code Playgroud) 我在子模块中有一个函数,它需要像这样操作来自父/解释器全局变量(断言、验证)的变量:
import mymodule
mymodule.fun_using_main_interpreter_globals1()
Run Code Online (Sandbox Code Playgroud)
如果我这样做,它会起作用:
mymodule.fun_using_main_interpreter_globals1(explicit_pass= globals() )
Run Code Online (Sandbox Code Playgroud)
但是,如果我不明确地传递 globals(),我如何才能将解释器/父 globals() 访问到我的子模块中?
在 IPython 中,它可以放在配置文件设置中。
我正在尝试使用闭包的属性在python中建立一个计数器。以下代码中的代码有效:
def generate_counter():
CNT = [0]
def add_one():
CNT[0] = CNT[0] + 1
return CNT[0]
return add_one
Run Code Online (Sandbox Code Playgroud)
但是,当我将列表CNT更改为var时,它不起作用:
def generate_counter1():
x = 0
def add_one():
x = x + 1
return x
return add_one
Run Code Online (Sandbox Code Playgroud)
当我打印实例的闭包属性时,我发现__closure__第二种情况是没有:
>>> ct1 = generate_counter()
>>> ct2 = generate_counter1()
>>> print(ct1.__closure__[0])
<cell at 0xb723765c: list object at 0xb724370c>
>>> print(ct2.__closure__)
None
Run Code Online (Sandbox Code Playgroud)
只是想知道为什么外部函数的索引必须是列表?
感谢您的回答!找到可以清楚说明此问题的文档 https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
python ×5
closures ×2
conditional ×1
ipython ×1
python-2.7 ×1
python-2.x ×1
regex ×1
scope ×1
variables ×1