Python范围规则究竟是什么?
如果我有一些代码:
code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
Run Code Online (Sandbox Code Playgroud)
在哪里x找到?一些可能的选择包括以下列表:
在执行期间,当函数spam在其他地方传递时,也存在上下文.也许lambda函数的传递方式有点不同?
某处必须有简单的参考或算法.对于中级Python程序员来说,这是一个令人困惑的世界.
在Python中我收到以下错误:
UnboundLocalError: local variable 'total' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
在文件的开头(在出现错误的函数之前),我使用global关键字声明'total'.然后,在程序的主体中,在调用使用'total'的函数之前,我将它指定为0.我已经尝试在各个地方将它设置为0(包括文件的顶部,就在它被声明之后) ),但我不能让它工作.有谁看到我做错了什么?
对于以下Python 2.7代码:
#!/usr/bin/python
def funcA():
print "funcA"
c = 0
def funcB():
c += 3
print "funcB", c
def funcC():
print "funcC", c
print "c", c
funcB()
c += 2
funcC()
c += 2
funcB()
c += 2
funcC()
print "end"
funcA()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
File "./a.py", line 9, in funcB
c += 3
UnboundLocalError: local variable 'c' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
但是,当我注释掉该行c += 3中funcB,我得到以下的输出:
funcA
c 0
funcB 0
funcC 2
funcB 4
funcC 6
end
Run Code Online (Sandbox Code Playgroud)
c在 …