如何在函数中创建或使用全局变量?
如果我在一个函数中创建一个全局变量,我如何在另一个函数中使用该全局变量?我是否需要将全局变量存储在需要访问的函数的局部变量中?
Python范围规则究竟是什么?
如果我有一些代码:
code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
Run Code Online (Sandbox Code Playgroud)
在哪里x找到?一些可能的选择包括以下列表:
在执行期间,当函数spam在其他地方传递时,也存在上下文.也许lambda函数的传递方式有点不同?
某处必须有简单的参考或算法.对于中级Python程序员来说,这是一个令人困惑的世界.
Python nonlocal语句做了什么(在Python 3.0及更高版本中)?
官方Python网站上没有文档,help("nonlocal")也没有用.
我从阅读文档中了解到,Python有一个单独的函数命名空间,如果我想在该函数中使用全局变量,我需要使用global.
我正在使用Python 2.7,我尝试了这个小测试
>>> sub = ['0', '0', '0', '0']
>>> def getJoin():
... return '.'.join(sub)
...
>>> getJoin()
'0.0.0.0'
Run Code Online (Sandbox Code Playgroud)
即使没有,事情似乎也很好global.我能够毫无问题地访问全局变量.
我错过了什么吗?另外,以下是来自Python文档:
全局语句中列出的名称不能定义为形式参数,也不能定义为for循环控制目标,类定义,函数定义或import语句.
虽然形式参数和类定义对我有意义,但我无法理解for循环控制目标和函数定义的限制.
以下代码给出了错误UnboundLocalError: local variable 'Var1' referenced before assignment:
Var1 = 1
Var2 = 0
def function():
if Var2 == 0 and Var1 > 0:
print("Result One")
elif Var2 == 1 and Var1 > 0:
print("Result Two")
elif Var1 < 1:
print("Result Three")
Var1 =- 1
function()
Run Code Online (Sandbox Code Playgroud)
我怎样才能解决这个问题?谢谢你的帮助!
我在这做错了什么?
counter = 0
def increment():
counter += 1
increment()
Run Code Online (Sandbox Code Playgroud)
上面的代码抛出了一个UnboundLocalError.
我正在尝试在Python 2.6中实现一个闭包,我需要访问一个非局部变量,但似乎这个关键字在python 2.x中不可用.如何在这些版本的python中访问闭包中的非局部变量?
test1 = 0
def testFunc():
test1 += 1
testFunc()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
UnboundLocalError:赋值前引用的局部变量'test1'.
错误说这'test1'是局部变量,但我认为这个变量是全局的
那么它是全局的还是本地的,如何解决这个错误而不将全局test1作为参数传递给testFunc?
给出以下代码:
def A() :
b = 1
def B() :
# I can access 'b' from here.
print( b )
# But can i modify 'b' here? 'global' and assignment will not work.
B()
A()
Run Code Online (Sandbox Code Playgroud)
对于B()函数变量中的代码,b在外部作用域中,但不在全局作用域中.是否可以b从B()函数内修改变量?当然我可以从这里读取它print(),但是如何修改呢?
我在函数中有以下代码:
stored_blocks = {}
def replace_blocks(m):
block = m.group(0)
block_hash = sha1(block)
stored_blocks[block_hash] = block
return '{{{%s}}}' % block_hash
num_converted = 0
def convert_variables(m):
name = m.group(1)
num_converted += 1
return '<%%= %s %%>' % name
fixed = MATCH_DECLARE_NEW.sub('', template)
fixed = MATCH_PYTHON_BLOCK.sub(replace_blocks, fixed)
fixed = MATCH_FORMAT.sub(convert_variables, fixed)
Run Code Online (Sandbox Code Playgroud)
添加元素stored_blocks工作正常,但我不能增加num_converted第二个子功能:
UnboundLocalError:赋值前引用的局部变量'num_converted'
我可以使用,global但全局变量是丑陋的,我真的不需要该变量是全局的.
所以我很好奇如何写入父函数范围内的变量.
nonlocal num_converted可能会完成这项工作,但我需要一个适用于Python 2.x的解决方案.
python ×10
scope ×4
closures ×3
python-2.x ×2
python-3.x ×2
function ×1
global ×1
python-2.7 ×1